开发者

jQuery click function can't find the selector

a = new object();
a.loadInt开发者_运维问答erface();

$("button").click(function() {
    a.doSomething();
});

The problem is that a.loadInterface() is what loads the button into the DOM, and it happens at the end of a $.post() because data from the server is needed to populate some attributes of the button.

So what I think is going on is, JavaScript reads the button.click detector but at that time there is no button for it to bind to.

Any ideas?


Your assessment of the problem is correct. A simple solution would be to use delegate. E.g.,

$(document).delegate('button', 'click', function() {
    a.doSomething();
});


Edit: more info on delegate and why it works on dynamically created elements after event binding can be found here: http://api.jquery.com/delegate/


I think you are right. If you are creating button in based on the data returned from the post, you'll need to bind event in the method that is executed after the success of the post.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜