【问题标题】:jQuery if statment on click event not working in Chrome but working in firefox browserjQuery if 语句 onclick 事件在 Chrome 中不起作用但在 firefox 浏览器中起作用
【发布时间】:2019-10-29 16:19:02
【问题描述】:

我已使用此代码隐藏和显示元素,但我的 JQuery 代码在 else 语句中无法在 chrome 中运行,但在 Firefox 浏览器中可以正常运行。

Code

$(document).ready(function(){
  $(".item-title").on("click",function () {
      $(this).next('div').children().toggle();
      $(this).children().children('.fa-plus-square').hide()
      $(this).children().children('.fa-minus-square').show()
      if ($(this).next('div').children().is(':hidden')){
          $(this).addClass('bb')
      }
      else {
          $(this).removeClass('bb')
      }
  })

不要在 if 语句中删除类

【问题讨论】:

    标签: jquery google-chrome if-statement conditional-statements


    【解决方案1】:
    $(document).ready(function(){
      $(".item-title").on("click",function () {
            var currentClickedObject = $(this);
          currentClickedObject.next('div').children().toggle();
          currentClickedObject.children().children('.fa-plus-square').hide();
          currentClickedObject.children().children('.fa-minus-square').show();
          if (currentClickedObject.next('div').children().is(':hidden')){
              currentClickedObject.toggleClass('bb');
          }
          else {
              currentClickedObject.toggleClass('bb');
          }
      });
      });
    

    【讨论】:

    • 更新了代码。最好使用切换类。您还错过了关闭 document.ready 函数的括号。
    • 为什么你认为toggleClass更好? “切换”的想法是交替某物的状态。如果您的代码中没有“if 语句”,“toggle”将是一个很好的解决方案。在“else”条件中包含toggleClass 实际上会造成破坏行为。请更新你的答案:)
    • 您好 Bruno,请查看代码的第 4 行并将其与 if 语句进行比较。对于这个特定的问题陈述,toggleclass 可以工作并且不会中断。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多