[英]Using .hide() and .show() in jQuery
In my program I have several very similar drop-down menus all with the same name (foo in the following example). 在我的程序中,我有几个非常相似的下拉菜单,它们都具有相同的名称(以下示例中为foo)。 On change they hide or show a nearby div tag depending on whether or not "ON" was selected. 更改时,它们是否隐藏或显示附近的div标签,具体取决于是否选择了“ ON”。
$('.togClass').hide();
$('[name*="foo"]').change(function(){
if ($('[value="ON"]').is(':selected')) {
$('.togClass').show('blind', 1000);
} else {
$('.togClass').hide(1000);
}
});
As it is, all of the div tags with class "togClass" toggle when any of the drop down menus choose "ON", is there a way that I can choose to show/hide only the nearby div to the drop-down that chooses "ON"(they are nested in the same div)? 照原样,当任何下拉菜单选择“打开”时,所有具有“ togClass”类的div标签都会切换,有没有一种方法可以让我选择仅显示/隐藏附近的 div到选择的下拉列表中“ ON”(它们嵌套在同一个div中)? I don't want to write a copy of this function for every div I want to hide. 我不想为每个要隐藏的div编写此函数的副本。
Here is how it works in the HTML: 这是它在HTML中的工作方式:
<select name="foo">
<option value="OFF">OFF</option>
<option value="ON">ON</option>
</select><br/>
<div class="togClass">
//Stuff
</div>
Ofcourse you can. 当然可以。 Check out the jquery doc about traversing: http://api.jquery.com/category/traversing/ It has a lot of great examples. 查阅有关遍历的jquery文档: http : //api.jquery.com/category/traversing/有很多很好的例子。
For your problem the solution could be: .closest() 对于您的问题,解决方案可能是: .closest()
$('div.togClass').hide();
$('select[name*="foo"]').change(function(){
if ($(this).val() == "ON") {
$(this).siblings('div.togClass').show('blind', 1000);
} else {
$(this).siblings('div.togClass').hide(1000);
}
});
You have to tell us a bit more about what "nearby" means. 您必须告诉我们更多有关“附近”的含义的信息。 But it appears that the fundamental piece you're missing is the use of $(this)
within the change
function. 但是似乎您缺少的基本功能是在change
函数中使用$(this)
。 Instead of identifying any .togClass
item, you want to identify a specific one relative to $(this)
-- the element being changed. 而不是标识任何 .togClass
项,而是要标识一个相对于$(this)
的特定项-被更改的元素。
Here's one way to do it with the assumption that the associated .togClass
div is the next one to be found in the DOM. 这是一种假设关联的.togClass
div是DOM中下一个发现的方法。
$('[name*="foo"]').change(function(){
if( $(this).is(':selected') ) { // relative to the selected item
$(this).next('.togClass').show('blind',1000);
} else {
$(this).next('.togClass').hide(1000);
}
});
Where you see .next()
you'll actually need the appropriate jQuery traversal methods -- unlikely to be the one I've randomly assumed in the example. 在您看到.next()
您实际上需要适当的jQuery遍历方法-不太可能是我在示例中随机假定的方法。
How about using .closest() ? 如何使用.closest()呢?
Should do the trick. 应该做到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.