2010-03-14 61 views
0

我有一個頁面,其中消息和關聯元素(響應,轉發等)都基於父級的數據庫ID共享一個類。jQuery不一致。通過具有多個類的元素上的類刪除

例如

<pre> 
<div id="recentMessages"> 
<div id="a3" class="message a3">this is a message</div> 
    <div id="a5" class="message a5">this is another message</div> 
</div> 
<div id="recentComments"> 
    <div id="a3" class="comment a3">this is a comment</div> 
    <div id="a5" class="comment a5">this is another comment</div> 
</div> 
<div id="recentActions"> 
    <div id="a3" class="action a3">tim posted a new message</div> 
    <div id="a4" class="action a4">sara forwarded a message to john</div> 
</div> 
</pre> 

有時我需要刪除具有相同ID的所有元素,所以我本來

 
    jQuery('div#'+id).remove(); 

但由於IDS都應該是有時會不消除所有的IDS獨一無二。 所以我添加了id作爲一個類。現在我用

 
    jQuery('div.'+id).remove(); 

但這似乎是約80%有效,有時div不會被刪除。 我不確定問題是因爲div有多個類,但是我需要這些類,因爲這是我在點擊某人時引用元素的方式。 例如,

 
jQuery('div.message').click(function(){ 
    get the id, send it to the server and get the message 
}); 

有什麼不對勁,我在這裏做什麼?還是有更好的方法來做到這一點?

回答

0

看起來像這是一個問題,使用已定義的變量調用函數。我沒有意識到這會造成問題。
例如:

jQuery('div','div#recentActions').click(function(){ 
    var removeId=jQuery(this).attr('id').replace('','a'); 
    removeDiv(removeId); 
}); 

function removeDiv(removeId){ 
    jQuery('div#a'+removeId).remove(); 
} 

我不能肯定地說,這是問題,但改變功能:

function removeDiv(cancelId){ 
    jQuery('div#a'+canceld).remove(); 
} 

似乎是工作。

相關問題