开发者

Apply Function To An Object Which Is Inserted By JQuery

I have a function, which appends a div into a div(2). Inside div(2) I have a span. if I click this span, a function shall be executed.(click() function)

Currently I can not apply any function by onclick(), if div(2) gets inserted by jQuery. If I insert div(2) directly (开发者_JAVA技巧hardcoded) I can execute the function.

How can I apply a function to an object which is inserted by jQuery?


Use delegate() to handle events for future elements — those which are not yet part of the DOM:

$(document).delegate(".div2 > span", "click", function () {
   // handle click event here
});


Ideally you want to have your jQuery code that inserts the element also attach the click handler.

So extend your function that calls

$(div).append(div2)

To also call

$(div2).find("span").click(function() {

});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜