0

I have problems with clicking on table headings (asc, dsc) when press the button for getting json ajax data from php which builds my table. I use function sortresult by table headings for sorting values in table. Function sort result builds my table. I recive json data successful.

If I don't use button for showing data (just a lit bit change code), automaticaly get json with ajax and creating the table then the clicking is working fine. What colud be the problem for not working with button?

So i have function:

 $(document).ready(function(){
     $('#submit').click(function(event){
         $('#headings th').click(function(){
             $('#results').html("");
         var id=$(this).attr('id');
         var asc =(!$(this).attr('asc'));
         $('#headings th').each(function () {
             $(this).removeAttr('asc');
         });
             if(asc) $(this).attr('asc','asc');
        sortResult(id, asc);
         });
     showResult();
 });
 });

Function sortResult:

 function sortResult(prop, asc){
      var val=null; 
      dataOut = dataOut.sort(function(a,b){
      if(asc) return (a[prop] > b[prop]);
          else return (b[prop] > a[prop]);
      });
      showResult();
 }

Function showresult:

 function showResult(){
      var html='';
      for (var i in dataOut){
           html +='<tr>'
           +'<td>'+dataOut[i].email+'</td>'
           ...
           +'</tr>'
      }
      html+='</table>'
      $('#results').html(html);
 }
4

2 回答 2

1

因为您动态创建元素,所以您需要注册事件on

$(document).ready(function(){
     $(body).on("click", "#headings th", function(){
         $('#results').html("");
         var id=$(this).attr('id');
         var asc =(!$(this).attr('asc'));
         $('#headings th').each(function () {
              $(this).removeAttr('asc');
         });
         if(asc) $(this).attr('asc','asc');
         sortResult(id, asc);
     });
     $('#submit').click(function(event){
       showResult();
     });
});
于 2013-10-10T19:16:45.723 回答
0

如果您单击的元素是由 ajax 请求添加的,您将需要使用 jQuery 'on' 而不是 'click'。

http://api.jquery.com/on/

$(document).ready(function(){
    $('#submit').click(function(event){
        $('#headings th').on('click', function(){
            $('#results').html("");
            var id=$(this).attr('id');
            var asc =(!$(this).attr('asc'));
            $('#headings th').each(function () {
                $(this).removeAttr('asc');
            });
            if(asc) $(this).attr('asc','asc');
            sortResult(id, asc);
        });
        showResult();
   });
});
于 2013-10-10T19:17:51.423 回答