我有可以在其中添加选项和添加选项新字段的表单。我为此使用JQuery。问题是添加的字段的删除按钮不起作用。
这是我的表格:
逻辑
我单击Add New
按钮,新行将添加工作
我单击Remove
它必须删除该行不起作用
$(function() {
//add row for options
$("#addnewoptinrow").click(function(e) {
e.preventDefault();
$('.newrow').append('<div class="row mt-3 newrowadded"><div class="col-md-8"><input name="options[]" type="text" class="form-control" placeholder="Option Name"></div><div class="col-md-2"><input name="optionsprices[]" type="number" class="form-control" placeholder="Price"></div><div class="col-md-2"><button type="button" class="removerow btn btn-danger" id="removerow">Remove</button></div></div>');
});
//Remove the row
$('.removerow').on('click', function(e) {
e.preventDefault();
$('.newrowadded').closest("div.row").remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-8">
<input name="options[]" type="text" class="form-control" placeholder="Option Name">
</div>
<div class="col-md-2">
<input name="optionsprices[]" type="number" class="form-control" placeholder="Price">
</div>
<div class="col-md-2">
<button class="addnewqtydiscmsgsave btn btn-primary" id="addnewoptinrow">Add New</button>
</div>
</div>
<div class="newrow"></div>
任何想法如何解决该删除操作?
最佳答案
您的代码中有两个问题:
对on()
的调用是missing the "selector" argument,这意味着以后没有动态添加的元素将没有click事件边界
您的删除逻辑需要相对于被单击的按钮执行
在.removerow
点击处理程序中尝试以下更改:
/*
Bind the click handler to all elements dynamically added that match the
.removerow selector
*/
$('body').on('click','.removerow', function(e){
e.preventDefault();
/*
Explaination:
1. from "this" remove button being clicked,
2. select the closest ".newrowadded" and,
3. remove it
*/
$(this).closest(".newrowadded").remove();
});
请参阅下面的代码片段,获取基于代码的工作示例:
$(function() {
//add row for options
$("#addnewoptinrow").click(function(e) {
e.preventDefault();
$('.newrow').append('<div class="row mt-3 newrowadded"><div class="col-md-8"><input name="options[]" type="text" class="form-control" placeholder="Option Name"></div><div class="col-md-2"><input name="optionsprices[]" type="number" class="form-control" placeholder="Price"></div><div class="col-md-2"><button type="button" class="removerow btn btn-danger">Remove</button></div></div>');
});
//Remove the row
$('body').on('click', '.removerow', function(e) {
e.preventDefault();
$(this).closest(".newrowadded").remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="row">
<div class="col-md-8">
<input name="options[]" type="text" class="form-control" placeholder="Option Name">
</div>
<div class="col-md-2">
<input name="optionsprices[]" type="number" class="form-control" placeholder="Price">
</div>
<div class="col-md-2">
<button class="addnewqtydiscmsgsave btn btn-primary" id="addnewoptinrow">Add New</button>
</div>
</div>
<div class="newrow"></div>
关于javascript - 未在附加按钮上调用JavaScript事件处理程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57422373/