我正在尝试克隆一个“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()
关于javascript - jquery 克隆并添加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47652130/