2014-04-01 43 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