【问题标题】:Click add class doesnt seem to be working单击添加类似乎不起作用
【发布时间】:2013-09-28 13:43:40
【问题描述】:

我正在尝试向单击的 div 添加一个类它似乎没有做任何事情? 这是我的jQuery

 $("#dropdown-nav").click(function () {

this.addClass('open');
    console.log('test');

});

【问题讨论】:

  • 始终使用您的控制台...
  • this.className="open" 或者当你使用 jQuery 时 $(this).addClass("open")
  • @mplungjan:第一个当然会删除任何其他类,如果存在的话...... :-)
  • 在使用 jquery-1.10.2.js 的控制台即时通讯上仍然无法正常工作,这会是个问题吗?
  • @ConnorCushionMulhall 等待文档就绪:$(function(){$("#dropdown-nav").click(function () { $(this).addClass('open'); console.log('test'); });}); 如果仍然无法正常工作,那么您正在动态添加元素(使用委托)或者您有多个具有相同 ID 的元素

标签: jquery class add


【解决方案1】:

你有一个明确的问题,由以前的答案标记,还有一个潜在的问题(你对 Abinash 的评论表明,按照他的建议去做,解决了第一个问题,并不能使它起作用)。

问题AaddClass是jQuery对象的方法,不是DOM元素,而是在click回调中this指的是一个DOM元素。要将其包装在 jQuery 对象中,请使用 $(this)jQuery(this)(在 noConflict 模式下)。请参阅之前的答案。

问题 B:如果仅此一项并不能解决问题,则最有可能的是,当您运行连接 @ 的代码时,dropdown-nav 元素还不存在987654329@ 处理程序。有两种方法可以确保它存在:

  1. 将包含连接代码的script 标签放在HTML 文件中的元素下方。通常,最好将脚本放在最后,就在结束 </body> 标记之前。或者,

  2. 使用 jQuery 的 ready 回调。

如果那些都没有解决,其他可能的解释是:

  • 该元素没有您认为的 id (dropdown-nav)
  • 其他东西挂住了click 事件并在您的代码看到它之前停止该事件
  • (到达这里)你忘了加载 jQuery

这是一个解决这两个问题的示例,使用问题 B 的解决方案 #1:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
  <style>
    .open {
      color: blue;
    }
  </style>
</head>
<body>
  <div id="dropdown-nav">Drop-down nav</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
// Note that this is BELOW the element in the HTML, so the element exists
$("#dropdown-nav").click(function() {
    $(this).addClass("open");
});
</script>
</body>
</html>

Live Copy

【讨论】:

    【解决方案2】:

    this 的语法错误。而不是

    this.addClass('open');
    

    $(this).addClass('open');
    

    jQuery(this).addClass('open');
    

    使用 jquery 时使用 $ 符号或前缀 jquery

    【讨论】:

      【解决方案3】:

      当你处理 jquery 时,this 应该是$(this)

       $("#dropdown-nav").click(function () {   
          $(this).addClass('open');
          console.log('test');    
      });
      

      看来,你刚刚开始使用 Jquery。

      学习:http://learn.jquery.com/javascript-101/this-keyword/

      【讨论】:

        【解决方案4】:

        你错过了$试试这个

        $(this).addClass('open');
        

        【讨论】:

          【解决方案5】:

          '#dropdown-navsounds like a large element to me. Are you sure it's not something like#dropdown-nav .menu-item`?无论如何,上述所有建议听起来都值得尊重和相关。以下是您可能想尝试的一件事:

          $("#dropdown-nav").on('click',function (e) {
              alert('You actually clicked on ' + e.target);
              $(this).addClass('open');
              console.log('test');
          });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-08-26
            • 2018-11-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-05-29
            • 1970-01-01
            相关资源
            最近更新 更多