我有一个 JavaScript 代码,我从使用 .live()
的旧代码中改编而来,将其更改为 .on()
,因为我使用 JQuery 1.9.1:
添加新的输入字段可以正常工作。问题是,单击删除时,它不会删除添加的字段。它甚至没有运行事件点击事件,我一直无法弄清楚为什么。
HTML 代码:
<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>
<div id="p_scents">
<p>
<label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
<a href="#" id="remScnt">Remove</a>
</p>
</div>
JS代码:
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').on('click', function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').on('click', function() {
alert('remove');
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
最佳答案
事件委托(delegate)。
并避免重复的 ID。
我已将它们更改为类。
HTML
<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>
<div id="p_scents">
<p>
<label for="p_scnts"><input type="text" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
<a href="#" class="remScnt">Remove</a>
</p>
</div>
JavaScript
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').on('click', function() {
$('<p><label for="p_scnts"><input type="text" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" class="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
return false;
});
$('#p_scents').on('click', '.remScnt', function() {
alert('remove');
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
关于javascript - 无法删除添加的输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16176636/