JQuery clone() and append()

徘徊边缘 提交于 2019-12-08 12:48:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!