我在文本框旁边有一个按钮,当我单击该按钮时,我希望它在另一个文本框旁边创建另一个按钮。这段代码就是这样做的,但新按钮不起作用。
<div id="algorithm">
<input type="button" id="add_child" value="+" />
<input type="text" id="textbox0" />
</div>
$('#add_child').click(function() {
$('<input type="button" id="add_child" value="+" />').appendTo('#algorithm');
$('<input type="text" id="textbox0" />').appendTo('#algorithm');
});
最佳答案
我建议尝试这种方法:
$('#algorithm').on('click','input',function(){
$(this).clone(true,true).insertAfter($(this));
});
修改了上面的代码以更新 id
属性以便没有重复项:
$('#algorithm').on('click','input',function(){
$(this).clone(true,true).attr('id','add_child' + $('input[type="button"]').length).insertAfter($(this));
});
引用资料:
- >
attr()
. - >
clone()
. - >
insertAfter()
. - >
on()
. - >
[attribute="value"]
selector .
关于javascript - 创建自身副本的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9830815/