[英]How can i use script parameters into my js file?
I have this script code: 我有以下脚本代码:
<script src="http://example.com/embed.js?q=123¶meter1=450¶meter2=300"></script>
How can i get the values of q(123)and parameter1(450) and parameter2(300) and use them into embed.js file? 我如何获取q(123)和parameter1(450)和parameter2(300)的值并将其用于embed.js文件? I want to make conditions into my embed.js by using these values. 我想通过使用这些值在我的embed.js中创建条件。 How can i achieve that? 我该如何实现?
Give the script element and ID attribute like this: 提供如下脚本元素和ID属性:
<script id="embed-script" src="http://example.com/embed.js?q=123¶meter1=450¶meter2=300"></script>
Javascript: Javascript:
var url = document.getElementById('embed-script');
function parseGet(val) {
var result = "",
tmp = [];
var items = url.src.split("?")[1].split('&');
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === val)
result = decodeURIComponent(tmp[1]);
}
return result;
}
Get the values like this, in embed.js: 在embed.js中获取如下所示的值:
var value1 = parseGet('q'); var value1 = parseGet('q');
value1 should then be "123". 那么value1应该是“ 123”。
I think you can't,but you can declare all param before required your js file same as: 我认为您不能,但是您可以在要求js文件之前声明所有参数,如下所示:
<script type="text/javascript">
var q = 123;
var parameter1 = 450;
var parameter2 = 300;
</script>
<script src="http://example.com/embed.js"></script>
You could place the parameters in attributes of the <script>
tag. 您可以将参数放在<script>
标记的属性中。
<script src="http://example.com/embed.js" q="123" parameter1="450" parameter2="300"></script>
You can access these parameters in embed.js
with 您可以使用以下命令在embed.js
访问这些参数
document.currentScript.getAttribute('q');
document.currentScript.getAttribute('parameter1');
document.currentScript.getAttribute('parameter2');
Note: document.currentScript
does not work on IE. 注意: document.currentScript
在IE上不起作用。
For more info check this out . 有关更多信息, 请查看此 。
You can access script
tag as the last script tag if ask for it without waiting for document load. 如果要求它,可以访问script
标签作为最后一个脚本标签,而无需等待文档加载。
~function() {
var s = document.querySelectorAll("script");
s = s[s.length-1];
console.log(s.src);
}();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.