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() {
});
精彩评论