窗口.打开参数作为变量

window.open parameters as a variable

本文关键字:变量 参数 窗口      更新时间:2023-09-26

在一个函数中,我有一行代码打开一个窗口,同时从函数自己的参数(u.n)或函数中创建的变量中提取其参数。

这在脚本中工作正常。

win2 = window.open(u, n, 'width=' + w + ', height=' + h + ', ' + 'left=' + wleft + ', top=' + wtop + ', ' + tools);

由于在脚本中多次调用它,但作为win3,win4等,为了减少代码,我想将每次都相同的参数放入一个变量中,并且每次都使用它。

myparameters =  u + ',' + n + ',width=' + w + ', height=' + h + ', ' + 'left=' + wleft + ', top=' + wtop + ', ' + tools;
win3 = window.open(myparameters);

我试过玩这个,但没有太多运气,能做到吗?

谢谢。

是的,在某种程度上,你可以通过将其包装在函数调用中。我通常做的是拥有一个实用程序函数,我可以在需要时调用它。

像这样:

popOpen: function (url, target, height, width) {
        var newWindow, args = "";
        args += "height=" + height + ",width=" + width;
        args += "dependent=yes,scrollbars=yes,resizable=yes";
        newWindow = open(url, target, args);
        newWindow.focus();
        return newWindow;
}

您可以通过使其成为类似以下内容的对象来进一步减少参数:

popOpen: function (params) {
        var newWindow, args = "";
        args += "height=" + params.height + ",width=" + params.width;
        args += "dependent=yes,scrollbars=yes,resizable=yes";
        newWindow = open(params.url, params.target, params.args);
        newWindow.focus();
        return newWindow;
}

你可以这样称呼它:

var param = { url: '...', height: '...', width: '...' };
popOpen(param);

var param = new Object;
param.url = '...';
param.height = '...';
popOpen(param);

你尝试的方式是不可能的。您可能希望这样做:

var myparameters =  'width=' + w + ', height=' + h + ', ' + 'left=' + wleft + ', top=' + wtop + ', ' + tools;
win3 = window.open(u, n, myparameters);

小提琴:http://jsfiddle.net/aBR7C/

函数调用中缺少一些其他参数:

var myparameters =  'width=' + w + ', height=' + h + ', ' + 'left=' + wleft + ', top=' + wtop + ', ' + tools;
win3 = window.open(u, n, myparameters);
                   ^  ^   ^
                 //Here you are passing parameters