开发者

Can't select added tr by jQuery

I add table and it's raws by jQuery when find result in database,and remove table when don't find anything.It works correctly.

$("#AdminSearch").bind("change keyup", function() { 
       var url = "http://localhost/PmMusic/index.php/admin/ajax/admin_search/"+$("#AdminSearch").val();
        $.getJSON(url,function(data){
            if (data.length == 0)
            {
                $("#AutoSearch").hide(1000);
                $("#AutoSearchTable").remove();
            }
            else
            {
                $("#AutoSearchTable").remove();
                $("#AutoSearch").append('<table id="AutoSearchTable">');
                for(var i = 0;i < data.length && i < 5;i++)
                    {
                     $("#AutoSearchTable").append('<tr><td id="TableSearchTR'+i+'" value="'+data[i]+'">'+data[i]+'</td></tr>');
                    }
                $("#AutoSearch").append('</table>');
                $("#AutoSearch").show(1000);    
            }
        });

    });

but when I wanna select tr by following code

    $('tr').click(function(){
        alert("Hi");
    });

When I click on other table tr in p开发者_运维知识库age it works,but it can't select tr which added by upper code). where is the problem?


You need to use .live() or .delegate() to attach click events to dynamically-created elements.

$("#AdminSearch").delegate("tr","click",function() {
    alert("Hi");
});


That's because you're binding with .click, which only applies to elements already in the page.

Change your code to

$('tr').live('click', function(){
    alert("Hi");
});


If the TR is not there when your .click() function is added, then it won't have a click event attached. You should look at using the .delegate() function instead.


click() will only work for elements already in the DOM. If you're loading in some content w/ ajax then I would suggest live().

$('tr').live('click', function() {
  alert("Hi");
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜