jquery events do not recognise js-added html components?
I'm using js to add form elements into the html document. For instance, I'm adding an entire <form>
to a table cell. Eg:
<form class="add-comment"><input type="subm开发者_JAVA百科it" /></form>
I try to use js to invoke events based on elements within that newly created form but nothing happens. I should get an alert box. What am I doing wrongly?
$('.add-comment').submit(function() {
alert('form submitted!');
});
Thanks. Hope I explained it well enough.
Are you adding the element after you register the submit event handler? You will need to register the event after each new element, unless you use the live method to add the event.
$('.add-comment').live('submit', function() {
alert('form submitted!');
});
This adds the event for all selected elements, even if they are added in the future.
http://api.jquery.com/live/
Newly-created elements do not have any event handlers attached to them. You'd have to select them and add the event handler after you've added them (eg. $('.add-comment', newparent).submit(submitfunction)
).
You can generally use .live(eventname, function)
to add event handlers for existing and future created elements. However you can't use .live('submit', ...)
in jQuery 1.3 due to how these events are implemented in browsers (technically, they don't ‘bubble’).
jQuery 1.4 does support live
against submit
(through a really ugly hack).
I've written a rather long blog post regarding this if you're not using jQuery 1.4. You have to wire up the newly added elements, since they were not there when the page loaded. It should give you an insight into what is happening with the .live()
method.
Of course adding the event to the element is common worst practice. Try to find out about publish/subscribe style event handling, which can take the place of using the live plugin.
Kyle is right, you should use the live event to add events to current and future DOM elements. However, as an alternative, you can add the event when you create the form element:
(jQuery 1.4 style)
$('<form>', {
id: 'myFormID',
name: 'myFormName'
}).submit(function(){ alert('form submitted'); })
.appendTo(myDiv);
精彩评论