2013-09-30 111 views
0

我有這塊標記。記住所有這些都來自數據庫。我已經使用foreach循環,並在我得到這些值jQuery當點擊關閉按鈕時,它只會隱藏該特定的div?

<div id="announcment-wrap"> 
    <div class="announcement-text"> 
    This is again a dummy 
    <a href="http://www.google.com">|&nbsp;click here</a> 
    <a id="close" href="#" class="close">X</a> 
    </div> 
    <div class="announcement-text"> 
    This is demo 3 
    <a href="http://www.google.co.in">|&nbsp;Demo3</a> 
    <a id="close" href="#" class="close">X</a> 
    </div> 
    <div class="announcement-text"> 
    This is demo 4 
    <a href="http://facebook.com">|&nbsp;Demo again</a> 
    <a id="close" href="#" class="close">X</a> 
    </div>  
</div> 

現在你可以看到有一個關閉按鈕<a id="close" href="#" class="close">X</a>。我想,當有人會點擊關閉按鈕,那麼它只會隱藏DIV() jQuery中,當我用

jQuery(document).ready(function($) { 
    jQuery('#close').click(function() { 
    jQuery('.announcement-text').hide(); 
    }); 
}); 

它是唯一的工作對於第一塊,也被隱藏了總所有塊?因此,有人可以告訴我怎麼做,當有人會點擊該關閉按鈕,它會隱藏特定block.Thanks

+0

你不能有相同的ID的所有錨元素,使用類instead.Check我答 –

+0

全部關閉按鈕具有相同的ID,所以如果你試圖將無法正常工作使用Id訪問所有關閉按鈕。而不是ID訪問他們使用類即.close –

回答

1

嘗試:

jQuery(document).ready(function($) { 
    jQuery('#close').click(function() { 
    jQuery(this).parent('.announcement-text').hide(); 
    }); 
}); 
+0

+1爲此使用父母而不是最接近。 –

1

標識的應該是唯一的,這樣使用類代替,並嘗試使用.closest()

<a href="http://www.google.co.in">|&nbsp;Demo3</a> 
<a class="close" href="#" class="close">X</a> 
-----^ 

jQuery(document).ready(function($) { 
    jQuery('.close').click(function() { 
    jQuery(this).closest('.announcement-text').hide(); 
    }); 
}); 
2

ID應該是唯一的,這樣使用選擇作爲.close不#lose

嘗試http://jsfiddle.net/devmgs/ZGjaj/

你的每一個文本是

<div class="announcement-text"> 
    This is again a dummy 
    <a href="http://www.google.com">|&nbsp;click here</a> 
    <a id="close" href="#" class="close">X</a> 
</div> 

使用

$(document).ready(function($) { 
    $('.close').click(function() { 
    $(this).closest('.announcement-text').hide(); 
    }); 
}); 
0

您需要使用即.close對所有關閉關閉工作或指定不同的ID所有的他們。

jQuery(document).ready(function($) { 
     jQuery('.close').click(function(){ 
jQuery(this).closest('.announcement-text').hide();});}); 
1

由於關閉按鈕位於div內,因此您可以使用.parent()函數來選擇div。

jQuery(document).ready(function($) { 
    jQuery('#close').click(function() { 
     jQuery(this).parent().hide(); 
    }); 
}); 

所有最好的!希望這可以幫助。

0

首先,您不能對所有關閉按鈕具有相同的ID,刪除重複的ID。 這贏得了;在IE7將不起作用<

$(document).ready(function($) { 
    $('.close').click(function() { 
    $(this).parent('.announcement-text').hide(); 
    }); 
}); 
相關問題