在我的jQuery中,我有一个用于创建删除按钮的按钮:
$("#add").click(function() {
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var removeButton = $("<input type=\"button\" id=\"remove\" class=\"btn\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(removeButton);
});
但是,当我使用PHP而不是jQuery手动添加删除按钮时
<div class='fieldwrapper' id=<? echo "field".$counter ?>
<input type='button' id='remove' class='btn' value='Remove'>
</div>
我已检查过fieldwrapper id
是否重叠,为什么它不起作用?谢谢。
$(document).ready(function() {
$("#config").validate();
$('#id').click(function() {
$(this).parent().remove();
});
$("#add").click(function() {
var intId = $("#configField div").length + 1;
var label = $("<label>Field Name:</label>");
var labelType = $("<label>Field Type:</label>");
var labelReq = $("<label>Require:</label>");
var labelTag = $("<label>Tag:</label>");
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var fName = $("<input type=\"text\" name=\"Name" + intId + "\" class=\"required\" />");
var fTag = $("<input type=\"text\" name=\"Tag" + intId + "\" class=\"required\" />");
var fReq = $("<select class=\"required\" name=\"Req" + intId + "\" ><option selected=\"\" value=\"\">Please Select</option><option value=\"1\">Yes</option><option value=\"0\">No</option></select>");
var fType = $("<select class=\"required\" name=\"Type" + intId + "\" ><option selected=\"\" value=\"\">Please Select</option><option value=\"txt\">Text</option><option value=\"int\">Numbers</option><option value=\"bool\">Boolean</option></select>");
var removeButton = $("<input type=\"button\" id=\"remove\" class=\"btn remove\" value=\"Remove\" />");
fieldWrapper.append('<br>');
fieldWrapper.append(label);
fieldWrapper.append(fName);
fieldWrapper.append('<br>');
fieldWrapper.append(labelType);
fieldWrapper.append(fType);
fieldWrapper.append('<br>');
fieldWrapper.append(labelReq);
fieldWrapper.append(fReq);
fieldWrapper.append('<br>');
fieldWrapper.append(labelTag);
fieldWrapper.append(fTag);
fieldWrapper.append('<br>');
fieldWrapper.append(removeButton);
$("#configField").append(fieldWrapper);
});
$('.remove').on('click', function() {
$(this).parent().remove();
});
});
<div class='fieldwrapper' id=<? echo "field".$counter ?>
<input type='button' id='remove' class='btn remove' value='Remove'>
</div>
答案 0 :(得分:1)
点击“#add”后,您才启动了删除按钮功能。通过将其与内部函数区分开来,并指定“delegate('click',”,您将确保每个.remove元素将始终删除其父元素
$("#add").click(function() {
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var removeButton = $("<input type=\"button\" id=\"remove\" class=\"btn remove\" value=\"Remove\" />");
fieldWrapper.append(removeButton);
});
$('.remove').delegate('click', function() {
$(this).parent().remove();
});