jQuery按钮显示/隐藏类,如果存在类

jQuery buttons to show/hide classes IF classes exist

本文关键字:存在 如果 隐藏 按钮 显示 jQuery      更新时间:2023-09-26

。。。提前为我拙劣的编码道歉,我还在玩这个。简言之,我正在尝试使用3个(未来可能还会有更多)按钮,当单独单击时,它们会显示具有特定.class名称的所有div(同时隐藏具有其他特定.class名称的其他div)。类似于虚假内容切换系统。

$("#mr-button-01").click(function() {
  $(".key-01").css({ "background":"#ff00ff" }).animate( "slow" );
  $(".key-02, .key-03").removeAttr('style');
  $(".info-01").show();
  $(".info-02, .info-03").hide();
return false;
});

现在,mr-button-01key-01是相同的元素(只有id和class用于样式)。对于每个不同的按钮都会重复此代码,只需关闭或专注于其他"info"类。可能不是最好的行动计划,但每个按钮都有不同的功能,并且有不同的"activated".css样式,所以我还不知道该如何处理。

要点:我正试图弄清楚如何检查页面上是否存在".info-01"。如果没有,我们保留,但一起取消切换按钮。类似。。。

if
  .info-01 DOES exist
  proceed with original ridiculous 'click sorting' thing
else
  .info-01 DOESN'T exist on the page
  .#mr-button-01 click does nothing
  .key-01 (aka #mr-button-01) has a "dead" .css style applied to it

我知道有":不是"和其他一些选项——我只是不清楚语法或处理这一问题的最佳方法。任何帮助都将不胜感激,并随时建议一种替代方法,一种更简洁的方法来消除肿胀等。

HTML,非常基础:

<div id="nigga">
  <a href="#" id="mr-button-01"><div class="key-01">Choice 01</div></a>
  <a href="#" id="mr-button-02"><div class="key-02">Choice 02</div></a>
  <a href="#" id="mr-button-03"><div class="key-03">Choice 03</div></a>
</div>

也许这就是你想要的:

$("#mr-button-01").click(function(){
    // Check if element with searched class exists
    if($('.info-01')){
        //Apply css to clicked button
        $(this).animate({'background-color', 'ff00ff'), 'slow', function(){
            //Open info-1
            $(".info-01").show();
            //Hide info-02 and info-03 if they are shown
            $(".info-02").hide();
            $(".info-03").hide();
        });
    }else{
        //If searched class doe's not exist
        $(this).addClass('dead css class name');
        return false;
    }
});

您的html和js似乎不太兼容,也许可以尝试以下方法:

<a href="#" class="mr-button" data-id="1"><div class="key key-1">Choice 01</div></a>
<a href="#" class="mr-button" data-id="2"><div class="key key-2">Choice 02</div></a>
<a href="#" class="mr-button" data-id="3"><div class="key key-3">Choice 03</div></a>

$(".mr-button").click(function() {
  $key = $(".key-" + $(this).attr("data-id")); // locate key using this data-id
  if($key.length != 0){ // if $key exists, do silly thangs
    $key.show();
    $(".key").hide();
  }
  return false;
});

它有点像html,但它是更可重用的代码。