jQuery 在克隆选择选项后获取数据 ID

jQuery get the data id after cloned select options

本文关键字:获取 数据 ID 选项 选择 jQuery      更新时间:2023-09-26

在html标记中,我有一个简单的选择选项标签。使用 jQuery,我在更改选项时获取数据 ID,并且工作正常。但我也有克隆选择选项的按钮。对于克隆的元素,在更改时执行警报数据 ID 不起作用。这是我的标记和 js 代码

网页代码

<table>
        <tr class="resource-data">
            <td>
                <select name="product" class="product-name">
                    <option value="apple" data-id="apple">Apple</option>
                    <option value="bus" data-id="bus">Bus</option>
                    <option value="car" data-id="car">Car</option>
                    <option value="duster" data-id="duster">Duster</option>
                </select>
            </td>
        </tr>
    </table>
    <button type="button" class="btn btn-success pull-right add-new-data"> Add </button>

JS代码

<script type="text/javascript">
    jQuery(document).ready(function(){
        var FirstRow = jQuery("table tr.resource-data:first").clone();
        jQuery('body').on('click','.add-new-data', function() {
            var ParentRow = jQuery("table tr.resource-data").last();
            FirstRow.clone().insertAfter(ParentRow);
        });
    jQuery('select.product-name').on('change', function(e) {
        id = $(this).find("option:selected").data('id');
        alert(id);
    });
    });
    </script> 

这也是小提琴链接。那么有人可以告诉我如何提醒克隆的数据 ID 吗?任何帮助和建议都将非常可观。谢谢

您需要使用事件委派将事件附加到动态添加的元素:

jQuery('body').on('change','select.product-name', function(e) {
    id = $(this).find("option:selected").data('id');
    alert(id);
});

工作演示

仅供参考,您还可以使用 .clone(true) ,true 也会复制事件处理程序。

下面是修改/更新的代码。

jQuery(document).ready(function () {
    jQuery('select.product-name').on('change', function (e) {
        id = $(this).find("option:selected").data('id');
        alert(id);
    });
    var FirstRow = jQuery("table tr.resource-data:first").clone(true);
    jQuery('body').on('click', '.add-new-data', function () {
        var ParentRow = jQuery("table tr.resource-data").last();
        FirstRow.insertAfter(ParentRow);
    });
});

小提琴