jQuery单击函数无法找到选择器。

时间:2022-09-22 17:08:49
a = new object();
a.loadInterface();

$("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.

问题是,a.loadInterface()将按钮加载到DOM中,它发生在$.post()的末尾,因为填充按钮的某些属性需要来自服务器的数据。

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.

我认为JavaScript会读取按钮。单击检测器,但此时没有绑定到它的按钮。

Any ideas?

什么好主意吗?

2 个解决方案

#1


3  

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/

#2


0  

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.

我认为你是对的。如果您正在根据post返回的数据创建按钮,则需要在post成功后执行的方法中绑定事件。

#1


3  

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/

#2


0  

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.

我认为你是对的。如果您正在根据post返回的数据创建按钮,则需要在post成功后执行的方法中绑定事件。