2017-04-13 16 views
-1

不刪除的段落我有這樣的事情在我的HTML的身體:JQuery的一個.remove()通過ID

<p id="test.txt"><a href="javascript:void(0);" class="disp">test.txt</a> [<a href="javascript:void(0);" class="del">x</a>]</p> 
<p id="test2.txt"><a href="javascript:void(0);" class="disp">test2.txt</a> [<a href="javascript:void(0);" class="del">x</a>]</p> 
<p id="test3.txt"><a href="javascript:void(0);" class="disp">test3.txt</a> [<a href="javascript:void(0);" class="del">x</a>]</p> 
<p id="test4.txt"><a href="javascript:void(0);" class="disp">test4.txt</a> [<a href="javascript:void(0);" class="del">x</a>]</p> 
<p id="test5.txt"><a href="javascript:void(0);" class="disp">test5.txt</a> [<a href="javascript:void(0);" class="del">x</a>]</p> 
<p id="test6.txt"><a href="javascript:void(0);" class="disp">test6.txt</a> [<a href="javascript:void(0);" class="del">x</a>]</p> 

這是有關jQuery代碼的一部分:

$('a').click(function(e) { 
    e.preventDefault(); 
    var myClass = $(this).attr("class"); 
    if (myClass==="del"){ 
     var idToDelete = $(this).parent().attr("id"); 
     alert(idToDelete); 
     $("#" + idToDelete).remove(); 
     return; 
    } 
}) 

,當點擊其中一個鏈接,它似乎正確地獲得ID,但是,段落不會從頁面中刪除。我錯過了什麼?

謝謝!

+2

你需要躲避期間,否則jQuery是尋找一個元素與test1'的'了'id'和類txt'或者你的'可以使用'最接近'('p')'。 ()# –

+0

是的,jQuery正在尋找一個id'test',它有類'txt' =>'$(「#text.txt」)' – sTx

+0

你也可以使用'$(this).parent()。remove直接我認爲,因爲satpal說 – sTx

回答

1

正如你可以遍歷元素去掉,只需使用

$(this).parent().remove(); 

原因$("#" + idToDelete).remove();不工作,因爲在idToDelete元字符.這需要與\\進行轉義。

請注意,您的代碼可以提高作爲

$('a.del').click(function(e) { 
    e.preventDefault(); 
    $(this).parent().remove(); 
}) 
+0

絕對完美!我知道這是我正在做的傻事。我也接受了你的建議,並在Jquery中使用了a.del選擇器。非常感謝! – Aommaster