声明 JavaScript 变量

Declaring javascript variables

本文关键字:变量 JavaScript 声明      更新时间:2023-09-26

以下两种声明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。 一旦我将其更改为声明变量的第一个版本,我的插件就会按预期工作,并且变量保持在它们的范围内。

这是为什么呢?

您是否错过了第一行的逗号?

如果这样做:

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

取而代之的是:

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

startInfo将成为全局变量。

尝试将它们全部放在同一行上,看看会发生什么。

请看一下声明javascript变量,这将非常有用。您的问题var shadowBox = $(this),您那里缺少逗号。