我有这个html产品代码:
<div id="new-product-content">
<div class="col-md-3 col-sm-6 col-xs-12">
// here code product
<div class="delete-product">
<a>Detele</a>
</div>
</div>
</div>
<div id="products-div">
jQuery代码:
$(document).ready(function() {
var i = 0;
$('.add-new-product').on('click', function() {
// here just clone the product when chick on (.add-new-product) button
// every thing is fine with clone
var $clone = $('#new-product-content > div').clone();
$clone.appendTo('#products-div');
i++;
// here I try to put id in each product
$('#new-product-content > div').attr('id', 'row'+ i);
// here to put id in
$('.delete-product > a').attr('id',i);
});
});
在jQuery代码中,我多次克隆了产品,然后为每个产品添加了ID,并为删除按钮添加了相同的ID,以便他可以根据需要删除它。
那么他添加产品后我需要删除什么?
答案 0 :(得分:0)
如果您使用.product
之类的类来定义产品,则不需要任何ID。
比起将jQuery的.on()
方法与动态事件委托结合使用,通过使用Event.target
从点击的.product
到.closest()
来删除元素:
jQuery($ => { // DOM ready and $ alias in scope
let i = 0;
const template_product = (html="") => `<div class="product col-md-3 col-sm-6 col-xs-12">
<div>${html}</div>
<button type="button" class="delete-product">Delete</button>
</div>`;
const addProduct = () => $('#products').append(template_product(`Product: ${++i}`));
const deleteProduct = (ev) => $(ev.target).closest('.product').remove();
$('.add-product').on('click', addProduct);
$('#products').on('click', '.delete-product', deleteProduct);
});
<button type="button" class="add-product">ADD PRODUCT</button>
<div id="products"></div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
我经常使用的另一种方法是预先声明“删除”按钮动作:
jQuery($ => { // DOM ready and $ alias in scope
const newProduct = (html='') => $('<div/>', {
class: 'product col-md-3 col-sm-6 col-xs-12',
html: `<div>${html}</div>`,
appendTo: '#products',
append: $('<button/>', {
class: 'delete-product',
type: 'button',
text: 'Delete',
click() {
$(this).closest('.product').remove();
}
})
});
let i = 0;
$('.add-product').on('click', () => newProduct(`Product: ${++i}`));
});
<button type="button" class="add-product">ADD PRODUCT</button>
<div id="products"></div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
即使它尊重模板和封装组件的原理-对于新开发人员来说,以上内容可能看起来有些复杂。