2017-01-05 40 views
0

我想将输入字段的值添加到属性data-value的值中。这实际上工作,但我有一个按钮,生成新的领域。因此,该值可以添加到第一个输入字段,但不会添加到通过单击按钮生成的值。添加属性对于克隆元素不起作用

<button id="another_field">Add a new field</button> 

<div class="cpt_area"> 
    <input placeholder="Type something here..." class="full_width cpt_name" type="text" name="cpt_name[]"> 
</div> 
// This will copy an input field 
$('#another_field').click(function() { 
    $('.cpt_name:first').clone().prependTo(".cpt_area").val(''); 
}); 

// This will generate a data-value attribute 
$('input').keyup(function() { 
    $(this).attr('data-value', $(this).val()); 
}); 

你可以在这里尝试一下:https://jsfiddle.net/e6ybk2d3/

任何想法如何,我可以解决这个问题?

+0

欢迎来到Stack Overflow。预期问题是自我包含的,而不仅仅是与外部资源的链接,所以当链接断裂时它们仍然有用。这次我为你编辑了这个问题。 –

回答

3

使用clone(true):如果您没有设置该参数withDataAndEvents作为

$('.cpt_name:first').clone(true)

事件处理程序将不会被克隆true,见th e doc here:https://api.jquery.com/clone/

+0

谢谢,修好了! – Reza

3

$('input')只会检测页面加载时出现的输入。克隆人将不会听取关键事件。

而不是

$('input').keyup(function() { 
    $(this).attr('data-value', $(this).val()); 
}); 

使用

$('.cpt_area').on('keyup', 'input', function(ev){ 
    $(this).attr('data-value', $(this).val()); 
}); 
+0

谢谢,那也帮助了我! – Reza