jQuery如果没有类不触发功能

jQuery if does not have class do not trigger function

本文关键字:功能 如果没有 jQuery      更新时间:2023-09-26

我将直奔主题。基本上,我有以下HTML结构:

<div id="global-container">
    <div class="content-pusher">
        <a class="mobile-menu-btn" href="#">Mobile menu btn</a>
    </div>
</div>

在 JavaScript/jQuery 之后:

$(function() {
    // Side panel.
    $('.content-pusher').click(function(e) {
        $this = $(this);
        if ($this.parents('#global-container').hasClass('side-panel-open'))
        {
            $this.parents('#global-container').removeClass('side-panel-open');
        }
    });
    $('.mobile-menu-btn').click(function(e) {
        e.preventDefault();
        $('#global-container').addClass('side-panel-open');
    });
});

问题是我想在单击Mobile menu btn时添加一个类side-panel-open #global-container,并在单击content-pusherdiv时将其删除。

问题:当我单击Mobile menu btn时,它会side-panel-open类添加到div #global-container并立即将其删除,因为Mobile menu btncontent-pusher 内部。(我不能把它放在那个div 之外)。

起初我认为$('.content-pusher').click...触发器早于$('.mobule-menu-btn').click...它应该可以工作,但事实并非如此,因为当我检查 #global-containerdiv 上是否有类side-panel-open时,它返回 TRUE,即使这个类被添加到该函数之后。

JSFiddle: http://jsfiddle.net/xFdKx/

我建议处理#global-container上的点击,并检查它们的来源:

$('#global-container').on('click', 'div.content-pusher, a.mobile-menu-btn', function(e){
    $('#global-container').toggleClass('side-panel-open', $(e.target).is('a.mobile-menu-btn'));
});

JS小提琴演示。

引用:

  • event.target (jQuery).
  • event.target (DOM)
  • is() .
  • on() .
  • toggleClass() .

您可以阻止从 mobile-menu-btn 元素传播单击事件

$(function () {
    // Side panel.
    $('.content-pusher').click(function (e) {
        //since you have the id of the element there is no need to use the parents method here
        $('#global-container').removeClass('side-panel-open');
        //$(this).parents('#global-container').removeClass('side-panel-open');
    });
    $('.mobile-menu-btn').click(function (e) {
        $('#global-container').addClass('side-panel-open');
        return false;
    });
});

演示:小提琴