jQuery $(document).click冲突

时间:2014-05-11 15:26:29

标签: javascript jquery responsive-design

我正在开发一个响应式网站。有两个函数:两者都使用嵌套函数,处理事件$(document).click()。两者都隐藏相同的元素 - .dropdown.slide-out。但是,在第一种情况下,函数引用选择器.dropdown,在第二种情况下引用选择器.slide-out.第一种情况仅适用于:我哪里出错?

/*
    |---------------------------------------
    | Dropdowns
    |---------------------------------------
    */
$(function () {
    var label = $('.dropdown-toggle');
    var allDropDowns = $('.dropdown-menu, .rmb-popup');
    var el = $(this);
    label.click(function () {
        if (Modernizr.mq('only screen and (min-width: 768px)')) {
            allDropDowns.hide();
            $(this).parents('.dropdown').children('.dropdown-menu').toggle('fast');
            label.removeClass('active');
            $(this).addClass('active');
            return false
        }
    });

    // Conflict point #1. Hide .dropdown.slide-out-right
    $(document).click(function () {
        allDropDowns.hide();
        label.removeClass('active');
    });

    allDropDowns.click(function (event) {
        event.stopPropagation();
    });
});
/*
    |---------------------------------------
    | Slide-outs
    |---------------------------------------
    */

$(function () {
    var soRight = $('.slide-out-right');
    $('.btn-menu-secd').click(function () {
        if (Modernizr.mq('only screen and (max-width: 767px)')) {
            soRight.animate({
                right: 0
            }, 400)
        }
        return false
    });

    // Conflict point #2. Slide out .dropdown.slide-out-right
    $(document).click(function () {
        if (Modernizr.mq('only screen and (max-width: 767px)')) {
            if (soRight.attr('style')) {
                soRight.animate({
                    right: '-270px'
                }, 400, function () {
                    soRight.removeAttr('style')
                })
            }
        }
    });

    soRight.click(function (event) {
        event.stopPropagation();
    });
});

1 个答案:

答案 0 :(得分:0)

UPD:我错了。 JQuery从1.7开始,在1个事件上附加多个或多个处理程序。它将按绑定Documentation

的顺序执行它

FIDDLE

1:

$(function(){
var allDropDowns = $('.dropdown-menu');
$('.dropdown-toggle').click(function() {
        allDropDowns.show();
        return false;
});
$(document).click(function() {   
    allDropDowns.hide();
});    
$('.dropdown-menu').click(function(e) {
        e.stopPropagation(); 
        e.preventDefault(); 
});
});

2:

$(function() {
var slideOut = $('.slideout');
$('.btn-menu').click(function() {
        slideOut.show();
        return false;
});
$(document).click(function() {
    slideOut.hide();
});
$('.slideout').click(function(e) {
    e.stopPropagation(); 
    e.preventDefault();
});
});