【问题标题】:Jquery will not select button after class has been toggled切换类后Jquery不会选择按钮
【发布时间】:2016-11-17 01:36:09
【问题描述】:

我有一些 jquery,当单击一个按钮时,它将一个类从一个按钮切换到另一个类(即在单击从 #testButton 切换类从 .first 到 .second 时,使用图像切换来显示它的工作原理) .第一次点击效果很好,它切换了图像,但第二次点击没有做任何事情。似乎它不承认新班级。这是一个小提琴。

https://jsfiddle.net/myfb44yu/

这是有问题的javascript。

$(document).ready(function(){
  $('.first').click(function(){
    alert('works');
    $('#testButton').toggleClass('first', 'second');
  });

  $('.second').click(function(){
    alert("works");
    $('#testButton').toggleClass('second', 'first');
  });
});

有趣的是,它在我使用 alert() 进行检查时有效,但在我尝试更改 img src 时无效。

【问题讨论】:

  • 标记中具有“第二”类的元素在哪里
  • $('.first') 返回一个数组
  • @Geeky 没有第二个元素,有一个元素的类在 .first 和 .second 之间交替。还有什么是 $(.'first') 返回数组的相关性?
  • 请参阅.toggleClass 文档。我的读物说要切换的多个类是在一个空格分隔的字符串中提供的。

标签: javascript jquery html


【解决方案1】:

您的主要问题是关于您的 .toggleClass 的语法错误,但鉴于其他人已经解决了这个问题,我想指出您应该考虑重新考虑如何应用您的听众 - 一样好习惯向前。


jQuery 事件绑定概述

将页面上的元素视为商店中的商品。你是一名员工,你的经理说“去给玩具部门的任何东西贴上红色标签”,你就这样做了。第二天,他在玩具部放了10个新玩具,对你说:“为什么不是所有的玩具都贴上红色标签?”然后他将其中一个玩具移到服装区并问你:“为什么这件玩具上有红色标签?”这很简单。你在玩具部门的任何东西上都贴上了红色标签当他告诉你这样做时 - 事情后来被转移了。

此示例中的玩具将是您的 .first.second 元素。

这就是 jQuery 事件绑定的工作方式——它们只适用于在事件初始化时满足选择器的元素。

所以,如果您执行$('.myClass').click();那么.myClass 放在五个按钮上 - 这些按钮都不会调用此函数,因为它们没有监听器。 p>

类似地,如果您使用类在一个元素上放置一个监听器,然后从该元素中删除该类,它将保持绑定事件


解决方案

$(document).on("click", ".first", function() { } );

这称为事件委托

继续我之前的类比,这相当于完​​全跳过对商品进行标记,而只是在客户将它们带到收银机时确定它们是否是玩具。

我们没有将侦听器放在特定元素上,而是将其放在整个页面上。通过使用".first" 作为第二个参数(它接受一个选择器),该函数将仅在元素具有类first 时执行。

希望这会有所帮助。

编辑:在我打字的时候,JHecht 留下了good answer,指出了我上面概述的相同问题。

【讨论】:

  • 太好了,非常感谢,在许多其他解决方案给了我其他想法、单击、添加、删除按钮类的方法之后,它终于对我有所帮助,但没有说我必须把文件上的监听器!在这里你甚至解释了它的原因......不幸的是我不能投票两次:)
【解决方案2】:

N 个元素可以具有相同的类名,这就是您尝试搜索它的原因,因为 $('.classname') 返回一个数组,这就是您的代码不起作用的原因。class selector

Id 是唯一的,每个元素都应该有一个 id 。在您的代码中,按钮有两个 id,对于同一个按钮,您尝试切换第一个和第二个,第一个和第二个不需要两个单独的事件

你可以写成下面这样

检查这个sn-p

$(document).ready(function() {
  var firstElements = $('.first')
  var first = firstElements[0];
  var secondElements = $('.second');
  var second = secondElements[0]

  $("#testButton").click(function() {
    alert('works');
    $(this).toggleClass('first').toggleClass('second');
  });



});
.first {
  color: red;
}
.second {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
  <button type="button" id='testButton' class='first'>Hi</button>
</div>

希望对你有帮助

【讨论】:

    【解决方案3】:

    关于这个解决方案。希望对您有所帮助!

    $(document).ready(function(){
    
        $("#testButton").click(function(){
            if($(this).prop("class") === "first"){
            alert('first');
             $(this).removeClass("first").addClass("second"); 
            }
            else if($(this).prop("class") === "second"){
             alert("second");
             $(this).removeClass("second").addClass("first");
            }
        });
    });
    .first{
        color: red;
    }
    .second{
        color: blue;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <img src="img/images.jpeg" alt="" id="testImage">
    <div id="testDiv">
        <button type="button" id='testButton' class='first'>Hi</button>
    </div>

    【讨论】:

      【解决方案4】:

      我希望我要说的比我感觉的更有意义。

      您的问题是,当您分配点击事件时,当前没有一个元素具有 .second 类。

      另外,您的代码是错误的。 toggleClass 接受几个参数,第一个是类字符串,第二个是可选参数,用于检查是否打开或关闭类。

      在不更改大量代码的情况下完成您想要的事情的一种方法是事件委托,如下所示。

      $(function() {
        $(document).on('click', '.btn-first,.btn-second', function() {
          //here we are adding the click event on the document object, and telling it that we only want to delegate this event to an object that matches the classes of .btn-first or .btn-second.
      
          //Note: to those saying "why not just do it on the .btn class an avoid having to do this", it is so he can see what delegation looks like. But you are correct, with this markup it would be better to simply add the click event on the .btn class.
          $(this).toggleClass('btn-first btn-second');
        });
      
      
      });
      .btn {
        padding: 4px 8px;
        border-radius: 3px;
        border: 1px solid grey;
      }
      .btn-first {
        background-color: green;
        border-color: green;
      }
      .btn-second {
        background-color: orange;
        border-color: orange
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <img src="img/images.jpeg" alt="" id="testImage">
      <div id="testDiv">
        <button type="button" id='testButton' class='btn btn-first'>Hi</button>
      </div>

      【讨论】:

        【解决方案5】:

        javascript、CSS 和 HTML 的组合,用于在单击“first”或“second”类的任何元素(包括测试按钮本身)时切换 #testButton 的类。发布的代码已更改为为 JQuery 的 .toggleClass 方法提供一个空格分隔的类名列表。点击“run sn -p”测试效果。

        $(document).ready(function(){
          $('.first').click(function(){
            $('#testButton').toggleClass('first second');
          });
        
          $('.second').click(function(){
            $('#testButton').toggleClass('first second');
          });
        });
        .first { border: thick outset green;}
        .second { border: thick inset red;}
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <p class="first">This paragraph has first class</p>
        <p class="second">This paragraph has second class</p>
        <button type="button" id="testButton" class="first">this button starts out first class</div>

        然后可以通过在一个选择器中组合多个类名来简化脚本,只留下:

        $(document).ready(function(){
            $('.first, .second').click(function(){
               $('#testButton').toggleClass('first second');
            });
        });
        

        【讨论】:

          【解决方案6】:
          • 创建一个按钮共享的中性类 (.btn)。
          • 然后将一个状态类添加到每个按钮(.first.second)。
          • 仅将点击事件委托给中性类 ($('.btn').on('click',...)。
          • 然后在this ($(this).toggleClass('first second');) 上切换两个状态类
          • 图片由 CSS 改变,每个按钮有 2 张图片,根据按钮的状态类在 display:none/block 之间交替。
          • 有一个例子是按钮外的图像,另一个例子是不切换类。

          片段

          $('.btn').on('click', function() {
            $(this).toggleClass('first second');
          });
          
          /* OR */
          $('.alt').on('click', function() {
            $('.img').toggle();
          });
          .first > .one {
            display: block;
          }
          .first > .two {
            display: none;
          }
          .second > .one {
            display: none;
          }
          .second > .two {
            display: block;
          }
          .first + .one {
            display: block;
          }
          .first + .one + .two {
            display: none;
          }
          .second + .one {
            display: none;
          }
          .second + .one + .two {
            display: block;
          }
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
          
          <p>Use jQuery with CSS</p>
          <button class='btn first'>
            <img src='http://placehold.it/50x50/000/fff?text=1' class='one'>
            <img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
          </button>
          
          <button class='btn second'>
            <img src='http://placehold.it/50x50/0e0/960?text=1' class='one'>
            <img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
          </button>
          <br/>
          <br/>
          
          <button class='btn first'>Toggle</button>
          <img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
          <img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
          
          
          <button class='btn second'>Toggle</button>
          <img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
          <img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
          
          <p>Or use only jQuery no CSS</p>
          <img src='http://placehold.it/50x50/0e0/930?text=1' class='img'>
          <img src='http://placehold.it/50x50/930/0e0?text=2' class='img' style='display:none'>
          <button class='alt' style='display:block;'>Toggle</button>

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-05-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-10-09
            • 2012-12-09
            • 1970-01-01
            相关资源
            最近更新 更多