这是一个非常仓促的概念证明。
我确信至少有2个地方可以改进,而且我也肯定这不会在野外长期存在。欢迎提供任何使它更美观或更有用的反馈。
关键是为脚本元素设置ID。唯一要注意的是,这意味着您只能调用一次脚本,因为它会寻找该ID来提取查询字符串。相反,如果脚本循环遍历所有查询元素以查看它们是否指向该查询元素,并且使用该脚本元素的最后一个实例,则可以修复此问题。无论如何,代码如下:
脚本被调用:
window.onload = function() {
//Notice that both possible parameters are pre-defined.
//Which is probably not required if using proper object notation
//in query string, or if variable-variables are possible in js.
var header;
var text;
//script gets the src attribute based on ID of page's script element:
var requestURL = document.getElementById("myScript").getAttribute("src");
//next use substring() to get querystring part of src
var queryString = requestURL.substring(requestURL.indexOf("?") + 1, requestURL.length);
//Next split the querystring into array
var params = queryString.split("&");
//Next loop through params
for(var i = 0; i < params.length; i++){
var name = params[i].substring(0,params[i].indexOf("="));
var value = params[i].substring(params[i].indexOf("=") + 1, params[i].length);
//Test if value is a number. If not, wrap value with quotes:
if(isNaN(parseInt(value))) {
params[i] = params[i].replace(value, "'" + value + "'");
}
// Finally, use eval to set values of pre-defined variables:
eval(params[i]);
}
//Output to test that it worked:
document.getElementById("docTitle").innerHTML = header;
document.getElementById("docText").innerHTML = text;
};
通过以下页面调用脚本:
<script id="myScript" type="text/javascript"
src="test.js?header=Test Page&text=This Works"></script>
<h1 id="docTitle"></h1>
<p id="docText"></p>