javascript 使用 jQuery“this”加上 CSS 选择器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24149181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using jQuery "this" plus a CSS selector?
提问by APAD1
I am writing a script to show/hide a section within a div. I have 3 of these divs with hidden sections but was hoping to use one function to control all 3.
我正在编写一个脚本来显示/隐藏 div 中的一个部分。我有 3 个带有隐藏部分的 div,但希望使用一个函数来控制所有 3 个。
Here's what I have right now:
这是我现在所拥有的:
$('.rates, .hours, .otherinfo').click(function() {
$('.expand').toggle();
});
Here's the HTML:
这是 HTML:
<div class="rates">
<h2>Rates</h2>
<div class="expand">
<p>Text in here is hidden by default.</p>
</div>
</div>
<div class="hours">
<h2>Hours</h2>
<div class="expand">
<p>Text in here is hidden by default.</p>
</div>
</div>
<div class="otherinfo">
<h2>Other Info</h2>
<div class="expand">
<p>Text in here is hidden by default.</p>
</div>
</div>
And CSS:
和 CSS:
.expand {
display:none;
}
Obviously, this shows the "expand" div for all 3 of the divs when you click on any of them. Is there a way to incorporate this
into the selector. Something like this'.expand'
?
显然,当您单击其中任何一个时,这会显示所有 3 个 div 的“展开”div。有没有办法合并this
到选择器中。像this'.expand'
什么?
Thanks!
谢谢!
回答by Nick
$(this).find('.expand').toggle()
$(this).find('.expand').toggle()
回答by Mark
You should add a fiddle for better answer. But something like this should work.
您应该添加小提琴以获得更好的答案。但是这样的事情应该有效。
$("#something").click(function(){$(this).children("section").toggle();});