javascript - jquery 克隆并添加事件

标签 javascript jquery jquery-clone

我正在尝试克隆一个“div”及其内部的所有内容,但其中一个事件在克隆的div中消失了(我对网络开发还很陌生,所以......我“克隆”了在SO上找到的代码) .
使用以下 JavaScript 添加缺失的事件:

var MyClass = document.querySelectorAll(".BtnOptList"); 
for (var ii = 0; ii < MyClass.length; ii++) {
    MyClass[ii].addEventListener('click', H_S_Btns_Func, false); 
}

然后,为了克隆 div,我使用以下函数:

$('#btnAddFlds').click(function () {
    //Count "cloned divs" we currently have 
    //This will be also used as numeric ID of the new input(s) field(s) (1st have no number)
    var DivNum = $('.SDetails').length; 
    // clone() element and update its id(s)
    var newElem2 = $('.SDetails:first').clone().attr('id', function( i, val ) {
                                                            return val + DivNum;
                                                            });
    // manipulate the id values of the input inside the new element
    newElem2.find('input,.BtnOptList,.HideIt').each(function(){
                                        $(this).attr('id', function( i, val ) {
                                                            return val + '_' + DivNum;
                                                            });
                                        });
    //Try to add function (DOESN'T WORK)
    newElem2.find('.BtnOptList').each().addEventListener('click', H_S_Divs_Func, false); 

    //I omitted other stuff
});

我已经尝试过克隆(true,true)但不起作用

最佳答案

根据文档,使用带有 true 的克隆意味着

A Boolean indicating whether event handlers and data should be copied along with the elements. (v1.4 onwards)

因此,使用

.clone(true)

而不是

.clone()

引用号:http://api.jquery.com/clone/

关于javascript - jquery 克隆并添加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47652130/

相关文章:

jquery - Bootstrap 药丸/标签和下拉菜单。不幸的婚姻?

javascript - 在调整大小的窗口中复制 div 中的内容会产生重复项

javascript - 使用克隆复制表行

javascript - jQuery 动画可以工作,但并不总是有效

javascript - 在哪里保存 api 的 JSON 响应?

javascript - 使用ajax选择产品名称后显示数据

jquery - 使用表单元素将页面加载到 div 并更新地址栏

Jquery 的多重选择器在 IE 中不起作用

javascript - 如何正确克隆字段集元素并将其附加到表单中?

javascript - 刷新数据表中的分页?