我可以将变量定义为参数吗?

时间:2012-12-13 13:14:32

标签: javascript jquery jquery-ui

我有以下jQuery UI功能的使用:

$('.droppable').droppable({
    tolerance: 'touch',
    over: function () {
        var hasHiddenList = $(this).children('ul.hidden');
        if (hasHiddenList.length)
            hasHiddenList.removeClass('hidden');
    },
    out: function () {
        var hasEmptyList = $(this).children('ul.empty');
        if (hasEmptyList.length)
            hasEmptyList.addClass('hidden');
    },
    drop: function () {
        var hasEmptyList = $(this).children('ul.empty');
        if (hasEmptyList.length)
            hasEmptyList.removeClass('empty');
    }
});

我想知道我是否可以在回调函数之外定义变量hasHiddenListhasEmptyList,因为它们在所有变量中都是相同的变量。

2 个答案:

答案 0 :(得分:5)

更好的是,你甚至不需要if语句和变量:

$('.droppable').droppable({
    tolerance: 'touch',
    over: function () {
      $(this).children('ul.hidden').removeClass('hidden');
    },
    out: function () {
      $(this).children('ul.empty').addClass('hidden');
    },
    drop: function () {
      $(this).children('ul.empty').removeClass('empty');
    }
});

答案 1 :(得分:1)

如果你真的想要变量,有两个选择。

显而易见的(有陷阱)是:

var hasHiddenList = $('.droppable').children('ul.hidden');
var hasEmptyList = $('.droppable').children('ul.empty');

$('.droppable').droppable({
    tolerance: 'touch',
    over: function () {
        if (hasHiddenList.length)
            hasHiddenList.removeClass('hidden');
    },
    out: function () {
        if (hasEmptyList.length)
            hasEmptyList.addClass('hidden');
    },
    drop: function () {
        if (hasEmptyList.length)
            hasEmptyList.removeClass('empty');
    }
});

已经提取了变量,代码重复性较低。一切都好。

现在,问题是选择器只运行一次。每次发生其中一个事件时,都会调用回调overoutdrop,但hasHiddenListhasEmptyList将不会更新;在每次调用之间它们仍然是相同的。可能不是你想要的。

解决这个问题的方法是使用函数而不是变量,如下所示:

var hiddenList = function(target) {
    return $(target).children('ul.hidden');
};
var emptyList = function(target) {
    return $(target).children('ul.empty');
};

$('.droppable').droppable({
    tolerance: 'touch',
    over: function () {
        var list = hiddenList(this);
        if (list.length)
            list.removeClass('hidden');
    },
    out: function () {
        var list = emptyList(this);
        if (list.length)
            list.addClass('hidden');
    },
    drop: function () {
        var list = emptyList(this);
        if (list.length)
            list.removeClass('empty');
    }
});

这抽象出了查询的执行方式(你只需要编写$(target).children('ul.empty');一次而不是两次)但实际上代码并没有真正变得简单。实际上,我甚至会说现在更难以遵循它。另一方面,如果你使用相同的选择器甚至超过两次,让我们说五次,那么这可能实际上是有用的。

另外,请注意我已从变量名中删除了“has”,因为“has”使它听起来像是布尔值,而它们不是。它们是元素列表。

相关问题