2009-12-22 83 views
0
<a rel="abc" href="#mydiv">link</a> 
<div id="mydiv">content</div> 

如果rel =「abc」,找到ID與href值匹配的元素並隱藏它。查找並隱藏div(jQuery)

我嘗試:

$('[rel*=abc]').attr("href").hide(); 

感謝您的幫助!

+0

同意發生,這聽起來確實很像功課 –

+0

我使用Facebox插件,我想隱藏內容的div自動上加載。這不是家庭作業,我可以發佈代碼,但在這種情況下,我不知道。 – 3zzy

+0

閱讀關於屬性選擇器的文檔:http://docs.jquery.com/Selectors –

回答

5
$($("a[rel='abc']").attr("href")).hide(); 
+0

不錯,比我剛剛寫的更好。也許把它放在$(document).ready(function(){})塊中。 – tsdbrown

+1

(如果您的ID包含'.'或':',注意將失敗。) – bobince

0
var identifier = $('a[rel="abc"]').attr('href'); 
$('#'+identifier').hide(); 

我認爲這可能會解決您的問題。雖然我沒有測試它。

+0

看起來像你有-1,因爲你的選擇器將是「## mydiv」 –

+0

不知道這是否是這種情況。謝謝你的提示。 –

2
$('a[rel=abc]').click(function(event){ 
    event.preventDefault(); 
    $(event.target.href.substr(event.href.indexOf('#'))).hide(); 
}); 

如果單擊此鏈接,則隱藏適當的元素。

編輯:測試

+1

可能想添加event.preventDefault()。或者至少返回假。 –

+0

當然。謝謝! – RamboNo5

2
$("a[rel='abc']").click(function(event){ 
    event.preventDefault(); 
    var val = $(this).attr("href"); 
    $("div"+val).hide(); 
}); 
1

$('a[rel=abc]').each(function() { $(this.href.substr(this.href.indexOf('#'))).hide(); });

一些錯誤檢查將是一件好事。

1
$("a[rel=abc]").each(function(i, ele) { 
    $(ele.hash).hide(); 
}); 

,或者如果你想,要在點擊

$("a[rel=abc]").click(function(e) { 
    e.preventDefault(); 
    $(this.hash).hide(); 
});