问题
I have a simple table:
<table id='table_actions'">
<tbody class='actions_body'>
<tr>
<td colspan=2 class="taskname"><strong>1. </strong><span name='taskname'>name</span></td>
</tr>
<tr>
<td>Действие: </td>
<td>
<select name='action_action'>
<option value="1">Consult</option>
<option value="2">Activate</option>
<option value="3">Connect</option>
</select>
</td>
</tr>
<tr>
<td><button id='addaction' class="btn">Добавить действие</button></td>
<td></td>
</tr>
</tbody>
</table>
And JQuery code:
$('#addaction').click(function() {
$('.actions_body tr:not(:last)').clone()
.insertBefore($('#table_actions tr:last'));
});
$('select[name=action_action]').change(function() {
alert();
});
My problem: by changing selection in the cloned part of the table, there is no alert.
回答1:
use the withDataAndEvents boolean parameter:
$('.actions_body tr:not(:last)').clone(true)
.clone( [withDataAndEvents] )
withDataAndEventsA Boolean indicating whether event handlers should be copied along with the elements.
docs
回答2:
The problem is because the change event is bound on page load, and the cloned elements are obvious not present at that time. You need to delegate the event handler to a parent. Try this:
$('#table_action').delegate('select[name=action_action]', 'change', function() {
alert();
});
Alternatively you can pass a boolean parameter to clone() to clone the element with it's attached events.
来源:https://stackoverflow.com/questions/12726443/jquery-clone-and-append