我正在使用jQuery并发现了一些问题。我有一个按钮,点击时会添加label
和span
。但是,当我尝试通过逐个单击来删除标签时,不会删除带逗号的跨度。我想在点击的标签后删除跨度。这是我的剧本。
$('#btn_add_vendor').on('click', function(){
var added = "<label class='label label-primary lbl_test'>MY LABEL</label><span class='add_comma'>,</span>";
$('#div_label').append(added); //the label appended here, in a div.
$('.lbl_test').click(function () {
$(this).remove();
$(this).next(".add_comma").remove(); //not working
});
});
答案 0 :(得分:3)
如果您先删除$(this)
,则$(this)
的引用将不再存在。
尝试更改顺序,并按照以下方式执行:
$('.lbl_test').click(function () {
$(this).next(".add_comma").remove();
$(this).remove();
});
答案 1 :(得分:1)
它不起作用,因为当您删除标签时,将找不到span作为其下一个元素。并且在点击方法上使用文档,因为元素是动态附加的。
请将您的代码更改为以下内容:
$('#btn_add_vendor').on('click', function(){
var added = "<label class='label label-primary lbl_test'>MY LABEL</label><span class='add_comma'>,</span>";
$('#div_label').append(added); //the label appended here, in a div.
$(document).on("click",".lbl_test",function () {
$(this).next(".add_comma").remove(); //REMOVE span FIRST
$(this).remove();//THEN REMOVE label
});
});
这样可行。
答案 2 :(得分:0)
在删除$('.lbl_test')
之前删除范围。
$('#btn_add_vendor').on('click', function(){
var added = "<label class='label label-primary lbl_test'>MY LABEL</label><span class='add_comma'>,</span>";
$('#div_label').append(added);
$('.lbl_test').click(function () {
$(this).next(".add_comma").remove();
$(this).remove();
});
});