3

以下两种声明javascript变量的方式有什么区别?

版本 1

var shadowBox = $(this);
var startInfo = shadowBox.children('.start-info');
var originalHeight = startInfo.height();

版本 2

var shadowBox = $(this),
    startInfo = shadowBox.children('.start-info'),
    originalHeight = startInfo.height();

我只问这个是因为我在 jquery 插件中使用了第二个版本:

(function ($) {
    $.fn.setUpShadowBox = function (options) {
        options = $.extend({
            boxSpeed: 750,
            boxWidth: 998,
            boxPosition: -40,
            heightSpeed: 500,
            scrollSpeed: 750
        }, options);

        return $(this).each(function () {
            var shadowBox = $(this),
                startInfo = shadowBox.children('.start-info'),
                originalHeight = startInfo.height();

            //rest of plugin code
        });
    };
});

但是当我在类选择器上使用它时,它必须循​​环不止一次,它将变量视为全局变量,并且只使用最后originalHeight设置的变量。一旦我将此更改为声明变量的第一个版本,我的插件按预期工作并且变量保持在其范围内。

为什么是这样?

4

2 回答 2

3

你错过了第一行的逗号吗?

如果你这样做:

var shadowBox = $(this)
    startInfo = innerContainer.children('.start-info');

而不是这个:

var shadowBox = $(this),
    startInfo = innerContainer.children('.start-info');

startInfo将成为全局变量。

试着把它们都放在同一条线上,看看会发生什么。

于 2013-11-12T12:34:07.763 回答
0

请看一下Declaring javascript variables,这将非常有用。你的问题是var shadowBox = $(this),你在那里缺少一个逗号。

于 2014-09-17T11:40:32.200 回答