在切换功能中,data() 或 attr('data-menu') 不起作用

in toggle function the data() or attr('data-menu') not work

我创建了一个简单的功能来切换菜单(有两个,一个在左边,一个在右边)。

如果我第一次切换,一切正常。

如果我第二次切换(关闭按钮),它找不到数据菜单属性。我不明白为什么先行后不行?

$('.dots-menu').toggle(
    function() {
      console.log( $(this).data('menu') )
      $( this ).children().addClass( "on" );
      $( '#dot-menu-event').addClass('open');
    }, function() {
      $( this ).children().removeClass( "on" );
      $( '#dot-menu-event').removeClass('open');
    }
  );

这是我的HTML代码

<div data-menu="event" class="dots-menu header absolute xbg-red-500 z-50 left-0 p-6">
            <button class="dots outline-none focus:outline-none"><span></span></button>

当我打印 $(this) 时,我实际上得到了 div 和 data-menu="event"

<div data-menu=​"event" class=​"dots-menu header absolute xbg-red-500 z-50 left-0 p-6">​…​</div>​

为什么JQuery又找不到数据菜单?我该如何解决这个问题?

Jquery toggle() 方法在 1.9 版本中被移除。所以你可以尝试我写的以下替代方法。这应该完全相同。

$.fn.toggleIt = function() {     
   var _args = arguments, i = 0;    
   $(this).click(function() {
      i = (i == _args.length) ? 0: i;
     _args[i++].call(this);
   });
};

这是一个例子

<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $.fn.toggleIt = function() {    
    var _args = arguments, i = 0;    
    $(this).click(function() {
        i = (i == _args.length) ? 0: i;
        _args[i++].call(this);
    });
  };
  
  $("p").toggleIt(
    function(){ $(this).css({"color": "red"});},
    function(){ $(this).css({"color": "blue"});},
    function(){ $(this).css({"color": "green"});
  });
  
});
</script>
</head>
<body>

<p style="font-size:40px">Click me.</p>

<div><b>Note:</b> Click to toggle between colors </div> 

</body>
</html>

尝试以下代码

$(document).on('toggle', '.dots-menu', function() {
        console.log( $(this).data('menu') )
        $( this ).children().addClass( "on" );
        $( '#dot-menu-event').addClass('open');
    }, function() {
        $( this ).children().removeClass( "on" );
        $( '#dot-menu-event').removeClass('open');
    }
);