1

I hava two divs. there is a button in div A and nothing in div B. a new button would be created in div B while I click button in div A. that is:

1) I click the button in div A;

2) the click would trigger a ajax message(jquery), and the message would be send to the background services(written by django);

3) the background services would return a html fragment, which is the new button in div B;

4) the new button would display in div B:

$("#B").empty();
$("#B").html(response);

the response is the html fragment(the html fragment includes the new button whose id is "bt_2").

5) I click the new button in div B;

6) I could not capture this click by using jquery:

$("#bt_2").click(function(tmp_event) {
    alert("get it!");
});

these js scripts are all in the same file(name is hp.js), and the js file is loaded successfully before I click the button in div A.

what should I do if I want to capture the click of the new button? any help would be appriaciate!

4

2 回答 2

1

因为#bt_2元素在加载 DOM 时不存在,所以您需要使用委托事件处理程序。尝试这个:

$('#B').on('click', '#bt_2', function(tmp_event) {
    alert("get it!");
});

我假设您在示例中提供的 ID 只是占位符?如果没有,您应该使它们对元素的描述性更强。

于 2013-08-13T09:19:48.537 回答
0

您可以像这样使用 .on() :

$("#B").on('click','#bt_2',function(tmp_event) {
    alert("get it!");
});
于 2013-08-13T09:20:02.820 回答