JQuery click事件删除ul li元素

时间:2014-04-01 12:02:45

标签: jquery

我有一个UL LI列表,当用户点击LI时,使用append会在LI旁边显示一个按钮。一个班级"选择"也将分配给李。 当用户点击另一个LI时,应删除之前带按钮的LI,并且该按钮将出现在新单击的LI上。但是我似乎无法删除prev LI的按钮。

我想从上一个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

});

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

以下代码将解决您的问题,

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

working sample

答案 2 :(得分: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>");
});

答案 3 :(得分: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();
});
相关问题