2014-04-01 117 views
0

我有一个UL LI列表,当用户单击LI时,将使用append在LI旁边显示一个按钮。 “选择”类也将分配给李。 当用户点击另一个LI时,应该删除先前的LI with按钮,并且该按钮将出现在新点击的LI上。但是我似乎无法删除prev LI的按钮。JQuery单击事件删除ul li元素

我想只是从前面的李删除按钮,并保持按钮在新选择的LI。我怎样才能做到这一点?我的代码如下。

在此先感谢。

$("ul#optionList li").on("click", function(){ 
    var test= $(this).attr('id'); 
    $("ul#optionList li").removeClass('selected'); 
    $(this).addClass('selected'); 

    // append the button to the LI 
    $(this).append("<a href='javascript:void(0);' class='checkanswer2' id='"+test+"'>Check Answer</a>"); 

    $(this).children("a").remove(); // this will caused all the buttons to be removed, not just removing the previous selected LI 

}); 
+1

提供您的HTML。 –

回答

1

与此

$("ul#optionList li").on("click", function(){ 
    var test= $(this).attr('id'); 
    $(this).siblings().removeClass('selected'); // remove other li class 
    $(this).addClass('selected'); // add class to clicked li 
    $(this).siblings().find("a").remove(); // remove other li a element 
    $(this).append("<a href='javascript:void(0);' class='checkanswer2' id='"+test+"'>Check Answer</a>"); 
}); 

DEMO

+0

非常感谢!它完美的工作! – Sylph

+0

@Sylph很高兴帮助你':-)' –

0

试试这个:

$("ul#optionList li").on("click", function(){ 
    var test= $(this).attr('id'); 
    $(".selected").find("a").remove(); 
    $("ul#optionList li").removeClass('selected'); 
    $(this).addClass('selected'); 
    $(this).children("a").remove(); // this will caused all the buttons to be removed, not just removing the previous selected LI 
    $(this).append("<a href='javascript:void(0);' class='checkanswer2' id='"+test+"'>Check Answer</a>"); 
}); 
+0

感谢您的帮助,得到了解决方案:) – Sylph

1

下面的代码将尝试解决您的问题,

$("ul#optionList li").not(".selected").children("a").remove(); 

working sample

+0

谢谢!你的方法也可以,但我只能接受一个答案 – Sylph

+0

@Sylph,没问题。如果你找到解决方案,就是这样:) –

0

尝试这样做:

$('ul#optionList').find('.checkanswer2').remove(); // remove the other anchors 
$(this).append("<a href='javascript:void(0);' class='checkanswer2'..."); 

可以追加,请先删除与类名.checkanswer2锚。


这样的:

$("ul#optionList li").on("click", function(){ 
    var test= $(this).attr('id'); 
    $("ul#optionList li").removeClass('selected'); 
    $(this).addClass('selected'); 
    $('ul#optionList').find('.checkanswer2').remove(); // remove the other anchors 
    $(this).append("<a href='javascript:void(0);' class='checkanswer2' id='"+test+"'>Check Answer</a>"); 
    $(this).children("a").remove(); 
}); 
+0

感谢您的帮助,得到了解决方案:) – Sylph