2017-03-17 134 views
2

我有一些javascript/jquery克隆表与一些输入文件和一个按钮。克隆后,按钮似乎不再工作了,当它有相同的类。克隆按钮不起作用

当前情况: 单击添加产品时,一行将被复制到最后一行下,以便用户可以将其他产品添加到该选项。这里是一个例子: enter image description here enter image description here

这些产品下面还有一个按钮:创建选项。该按钮克隆第一个表格(选项)并在该按钮下方显示。但它被复制后,按钮'添加产品'似乎不再工作 enter image description here

我没有任何错误,所以我不知道我在做什么错。

这是代码,我使用克隆表:

<script type="text/javascript"> 
$(document).ready(function() { 
    $('.addproduct').click(function (e) { 
     // Clone a product and add it to the option. 
     e.preventDefault(); 
     var item = document.getElementById('hiddenTemplate').cloneNode(true); 
     $('#hiddenTemplate').before(item); 
     $(item).removeAttr('id'); 

    }); 
    $('.addOption').click(function (e){ 
     // Create a new option 
     e.preventDefault(); 
     var item = document.getElementById('hiddenOption').cloneNode(true); 
     $('.newOption').append(item); 
     $(item).removeAttr('id'); 
     $(item).addClass('tableOptions'); 
    }); 
}); 

能some1向我解释我在做什么,什么可能是一个解决方案吗?我的代码并不完美,我认为我很乐意学习!

快乐编码!

+1

'cloneNode()'不会复制事件处理程序。我建议使用jQuery的'clone(true)'来代替,或者使用委托事件处理程序。后者将是最简单的。 –

+0

每当您生成动态html时,事件不会受到限制,因为在生成网页之前所有事件都有界限。因此需要事件委派,即将事件添加到父元素。检查@Ameya Deshpande的答案。 –

+0

“创建选项”按钮是否重新使用'.addproduct'点击代码?如果没有,这将有助于您发布它以及相关的HTML – Pineda

回答

1

使用document.on当你添加动态元素到DOM

$(document).on('.addproduct','click', function (e) { 
     // Clone a product and add it to the option. 
     e.preventDefault(); 
     var item = document.getElementById('hiddenTemplate').cloneNode(true); 
     $('#hiddenTemplate').before(item); 
     $(item).removeAttr('id'); 

    }); 

    $(document).on('.addOption','click',function (e){ 
     // Create a new option 
     e.preventDefault(); 
     var item = document.getElementById('hiddenOption').cloneNode(true); 
     $('.newOption').append(item); 
     $(item).removeAttr('id'); 
     $(item).addClass('tableOptions'); 
    }); 
+0

当我使用您的代码时,'hiddenOption'不会被克隆。 –

+0

你调试过吗? –

+0

Jep,没有错误+如果我看看代码中没有新的tr –