简体   繁体   English

如果此div具有此类,则隐藏另一个元素

[英]If this div has this class, hide another element

I want to hide the button ONLY if a specific div (.variable-item-3) has the class "selected". 我想隐藏只有在特定的div(.variable项-3)具有“选择”之类的按钮。

The class "selected" is added when the li is clicked. 单击li时,将添加“ selected”类。

 if($('.variable-item-3').hasClass('selected')) { $('.button').hide(); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li class="variable-item-1">Option 1</li> <li class="variable-item-2">Option 2</li> <li class="variable-item-3 selected">Option 3</li> </ul> <button type="submit" class="button">Add to cart</button> 

You need to perform the test after you change the selected class. 更改selected班级后,需要执行测试。 You're just running it once when the page is loaded, it won't automatically run again when the class changes. 您仅在页面加载时运行一次,而在类更改时不会自动再次运行。

You can use the .toggle() function with a boolean argument to make the visibility depend on a test. 您可以将.toggle()函数与布尔参数一起使用,以使可见性取决于测试。

 $("li").click(function() { $("li").removeClass("selected"); $(this).addClass("selected"); $(".button").toggle(!$('.variable-item-3').hasClass('selected')); }); 
 li.selected { background-color: yellow; } .button { display: none; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li class="variable-item-1">Option 1</li> <li class="variable-item-2">Option 2</li> <li class="variable-item-3 selected">Option 3</li> </ul> <button type="submit" class="button">Add to cart</button> 

Since you are already using javascript to add the .selected class, it's probably easier to use the javascript solutions suggested in the other answers. 由于您已经在使用javascript添加.selected类,因此使用其他答案中建议的javascript解决方案可能会更容易。 However, if you prefer using CSS (I personally prefer using CSS to Javascript whenever possible) and if the div you care about comes before the button you care about then you can actually just use CSS. 但是,如果您喜欢使用CSS(我个人更喜欢在可能的情况下使用CSS而不是Javascript),并且如果您关心的div在您关心的按钮之前 ,那么您实际上可以只使用CSS。

.variable-item-3.selected ~ .button {
  display: none;
}

This assumes that .button and .selected are siblings. 假定.button.selected是同级。 It gets more complicated if the two aren't siblings but it's still possible as long as an ancestor of .button is a sibling of .selected . 它变得更加复杂,如果两个都没有兄弟姐妹,但它仍然是可能的,只要的祖先.button是同级.selected In that case it would look something like this: 在这种情况下,它将看起来像这样:

.variable-item-3.selected ~ div .button {
  display: none;
}

If the HTML isn't structured so that either of these will work, then you'll need to use one of the other solutions that does it with javascript. 如果未对HTML进行结构化,以使其中任何一种都可以使用,那么您将需要使用使用javascript进行处理的其他解决方案之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM