问题
Possible Duplicate:
jQuery - Click event doesn’t work on dynamically generated elements
I just have a clickable add button that adds new table rows. The table rows include a delete button. I've noticed that when I dynamically add a new row the button does not fire the click event, but if the button exists when the page loads, then it works fine. How can I correct this?
Javascript:
$('#btnAdd').click(function () {
var newTr = '<tr><td><input id="column_0" name="column[0]" style="width:40%;" type="text" /> <img alt="Delete-icon24x24" class="btnDel clickable" id="" src="/assets/delete-icon24x24.png" /></td></tr>';
$('#columns').append(newTr);
});
$('.btnDel').click(function () {
alert('hey');
console.log('test');
var row = $(this).closest("tr");
alert(row);
row.remove();
});
回答1:
You'll need to use event-delegation:
$("table").on("click", ".btnDel", function () {
/* Respond to click here */
});
The reason is that you cannot bind a handler to items that don't presently exist in the DOM. You can, however, bind a handler to a delegate target (a parent element that will remain in the DOM). Clicks will bubble up the DOM, eventually reaching the delegate target.
We listen for clicks on the table
and we evaluate whether they came from an .btnDel
element. This will now respond to clicks from .btnDel
elements loaded when the page loaded, as well as those that are added dynamically later.
Lastly, don't re-use ID values.
回答2:
You need to use on() for event delegation for dynamically added html elements. You can delegate event to parent
element of dynamically added elements if you can or you can delegate to document
.
$(document).on('click', '.btnDel', function () {
alert('hey');
console.log('test');
var row = $(this).closest("tr");
alert(row);
row.remove();
});
Delegated events
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
For further understanding read this article Understanding Event Delegation
回答3:
use on()
$(document).on('click', '.btnDel', function(){
//your code
})
回答4:
This will work
$('#btnAdd').click(function () {
var newTr = '<tr><td><input id="column_0"
name="column[0]"style="width:40%;"type="text" />
<img alt="Delete-icon24x24" class="btnDel clickable" id=""
src="/assets/delete- icon24x24.png" /></td></tr>';
$('#columns').append(newTr);
$('.btnDel').click(function () {
alert('hey');
console.log('test');
var row = $(this).closest("tr");
alert(row);
row.remove();
});
});
来源:https://stackoverflow.com/questions/14351636/jquery-click-event-not-working-for-dynamic-fields