2

我正在尝试克隆一个“div”并将其全部包含在其中,但是其中一个事件在克隆的 div 中消失了(我对 Web 开发很陌生,所以......我“克隆”了在 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
});

我已经尝试过 clone(true,true) 但没有用

4

2 回答 2

4

根据使用克隆true手段的文档

一个布尔值,指示是否应将事件处理程序和数据与元素一起复制。(从 v1.4 开始)

因此,使用

.clone(true)

代替

.clone()

参考:http ://api.jquery.com/clone/

于 2017-12-05T11:15:44.727 回答
1

这 ( newElem2.find('.BtnOptList').each().addEventListener('click', H_S_Divs_Func, false);) 不是您使用 jQuery 的方式each。看看https://api.jquery.com/each/

剧透: newElem2.find('.BtnOptList').each(function(i,e){e.addEventListener('click', H_S_Divs_Func, false)})

PS:由于您使用的是 jQuery,您可以使用它自己的事件方法并将侦听器添加到整个列表中:

newElem2.find('.BtnOptList').on('click', H_S_Divs_Func, false)

于 2017-12-05T11:11:45.857 回答