hasClass()总是返回false(jquery),即使切换它也是如此

时间:2017-03-23 02:38:09

标签: javascript jquery html css

它为控制台的每个日志打印出false。单击导航链接和取消按钮时,切换工作正常。我查看this question并尝试了所有建议,但仍然遇到了同样的问题。



// add new photo toggle
$('#click_new_photo a').click(function() {
  console.log($(".content").hasClass('show-new-photo'));
  $(".content").find(".new-photo").toggleClass('show-new-photo');
  console.log($(".content").hasClass('show-new-photo'));
});

$("#cancel_add_new_photo").click(function() {
  console.log($(".content").hasClass('show-new-photo'));
  $(".new-photo").toggleClass("show-new-photo");
  console.log($(".content").hasClass('show-new-photo'));
});

.new-photo {
  width: 300px;
  height: 200px;
  border-radius: 5px;
  background: #34609d;
  box-shadow: 1px 1px #d6d6d6;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  z-index: 100;
  transition: opacity 0.5s ease;
  opacity: 0;
}

.show-new-photo {
  opacity: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <nav>
    <ul>
      <li id="click_new_photo"><a href="#">New Photo</a></li>
    </ul>
  </nav>
  <div class="content">
    <div class="new-photo">
      <button id="cancel_add_new_photo">Cancel</button>
    </div>
    ...
  </div>
  ...
</body>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

我相信

$(".content").find(".new-photo").toggleClass('show-new-photo');

只切换'.new-photo'元素上的'show-new-photo'类,而不是“.content”元素。

除非我遗漏了什么

console.log($("content").hasClass('show-new-photo'));
无论是在

之前还是之后,

都会出现同样的问题

$(".content").find(".new-photo").toggleClass('show-new-photo');

因为该行代码不会改变$(“。content”)是否具有“show-new-photo”类。

它也应该是$(“。content”),而不是$(“content”)。

答案 1 :(得分:2)

hasClass方法不适用于子节点。

你可以使用类似的东西

return $(".content").find('.show-new-photo').length > 0; 

答案 2 :(得分:1)

尝试

console.log($(".content").hasClass('show-new-photo'));

我相信这应该可以通过添加类“。”来实现。在你的选择器

相关问题