<script src="myscript.js?someParameter=123"></script>
从myscript.js
中,有没有办法获取someParameter
被设置为123
?或者唯一的方法是使用生成带有参数的javascript文件的服务器端脚本?
<script src="myscript.js?someParameter=123"></script>
从myscript.js
中,有没有办法获取someParameter
被设置为123
?或者唯一的方法是使用生成带有参数的javascript文件的服务器端脚本?
要获取URL参数,可以使用 window.location.href
。从名称上看,它指的是当前窗口。而<script>
标签的作用是将链接的文件嵌入到当前文档中,因此在同一窗口内。如果你从链接的JavaScript文件中解析window.location.href
,你只能获取到嵌入文档的URL。
有两种方法可以将参数传递给另一个JavaScript文件:
window
实例。<script>
标签将是“当前”标签的事实。然后作者将参数隐藏在class
属性中,而一篇文章的链接从src
属性中提取它们。我想那是可能得到的最接近的方法了。 - Vilx-data-
属性的HTML元素。您可以将它们放在<script>
标签上,或者如果您的脚本需要一个目标元素来工作,您也可以将其设置在该元素上。 - Vilx-$.each($('script'), function(id, val){ //loop trough all script-elements
var tmp_src = String($(this).attr('src'));//store the src-attr
var qs_index = tmp_src.indexOf('?');//check if src has a querystring and get the index
//Check if the script is the script we are looking for and if it has QS-params
if(tmp_src.indexOf('myscript.js') >= 0 && qs_index >= 0)
{
//this is myscript.js and has a querystring
//we want an array of param-pairs: var1 = value1, var2 = value2, ...
var params_raw = tmp_src.substr(qs_index + 1).split('&');
//create empty options array
var options = [];
//loop troug raw params
$.each(params_raw, function(id, param_pair){
//split names from values
var pp_raw = param_pair.split('=');
//store in options array
options[pp_raw[0]] = pp_raw[1];
});
//check the results out in the console!
console.log(options);
}
});
我希望这能满足你的需求?