[英]Showing a div on button click
我只是想在按下按鈕時toggle()
<div class="reveal">
。
我將在頁面上具有多個按鈕和相應的<div>
,所以我只想使用$(this).next("div.reveal").toggle();
在頁面上toggle()
下一個實例$(this).next("div.reveal").toggle();
沒有任何反應,也沒有錯誤。 我做錯了什么?
HTML:
<article class="customerQuotes">
<blockquote>Blah
<cite><b>Name</b> - Company</cite>
</blockquote>
<button class="button right">More</button>
</article>
<div class="reveal">
<div class="right">
//stuff here
</div>
</div>
JS:
$(".button").click(function() {
$(this).next("div.reveal").toggle();
});
CSS:
.reveal{
display: none;
float: left;
clear: both;
}
您需要在父元素上調用.next
,因為.reveal
是它的兄弟。
$(".button").click(function() {
$(this).parent().next("div.reveal").toggle();
});
那是因為$(this).next("div.reveal")
是undefined
。 按鈕元素旁邊沒有div.reveal
。
您將需要像這樣重組HTML:
<article class="customerQuotes">
<blockquote>Blah
<cite><b>Name</b> - Company</cite>
</blockquote>
<button class="button right">More</button>
<!-- Note here that div.reveal is sibling to a button so
.next() will find this element -->
<div class="reveal">
<div class="right">
//stuff here
</div>
</div>
</article>
或更改您的JQuery選擇器以像這樣從父元素中獲取下一個顯示:
$(".button").click(function() {
$(this).parent().next("div.reveal").toggle();
});
就像其他人說的那樣,您忘記了在parent()上使用next()方法。
但是,無論何時更改HTML的結構,此代碼都會中斷! 更好地引用要顯式揭示的元素。 一種簡單的方法是將目標另存為按鈕上的數據:
<button data-target="#reveal1" class="button right">More</button>
...
<div id="reveal1"></div>
然后,您的JS將如下所示:
$(".button").click(function() {
$( $(this).data("target") ).toggle();
});
無論您將按鈕和div放置在何處,這都將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.