jQuery writing input button append
I'm writing an input button with the following code:
$("#QnA").append("<input type='button' name='que开发者_JS百科stionSub' value='Save'/>");
What I would like to do it capture the click function of that new button. This is what I attempted:
$('input[name=questionSub]').click(function () {
alert('hi');
});
This isn't working for me. Any ideas?
You need to use jQuery's live method for newly created elements
$('input[name=questionSub]').live("click", function () {
alert('hi');
});
You can attach the click handler when you create it, like this:
$("<input type='button' name='questionSub' value='Save'/>").click(function() {
alert('hi');
}).appendTo("#QnA");
You can only bind an event to an element after the element has been created so make sure that the click binding occurs after the input has been appended.
It works for me. (jsFiddle Example)
Just make sure you call the click function after you've appended the input
button.
Edit:
You only need to use live() if you want to bind the click function before you append the input, since live() will attach a handler to the event for all elements which match the current selector, now or in the future.
jsFiddle Example
精彩评论