我在脚本路径中的不同查询字符串的页面中添加我的Javsacript文件,如下所示:
第1页:
<script type="text/javascript" src="file.js?abc=123"></script>
Run Code Online (Sandbox Code Playgroud)
第2页:
<script type="text/javascript" src="file.js?abc=456"></script>
Run Code Online (Sandbox Code Playgroud)
第3页:
<script type="text/javascript" src="file.js?abc=789"></script>
Run Code Online (Sandbox Code Playgroud)
在我的Javascript文件中,如何获取"abc"参数的值?我尝试使用window.location,但这不起作用.
如果有帮助,下面是我用来查找查询字符串参数值的函数:
function getQuerystring(key, defaultValue) {
if (defaultValue == null) defaultValue = "";
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
var qs = regex.exec(window.location.href);
if (qs == null)
return defaultValue;
else
return qs[1];
}
Run Code Online (Sandbox Code Playgroud)
Ash*_*ley 31
这个有可能.请参阅通过src属性传递JavaScript参数.最重要的是,由于HTML(而不是 XHTML)中的脚本是在加载时执行的,这将允许脚本找到自己,因为它始终是页面中的最后一个脚本 - 当它被触发时 -
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
// myScript now contains our script object
var queryString = myScript.src.replace(/^[^\?]+\??/,'');
Run Code Online (Sandbox Code Playgroud)
然后,您只需应用查询字符串解析.
jos*_*736 14
首先,技术答案:如果为脚本标记分配ID,则可以获取它src,然后解析出查询字符串.
<script id="whatever" type="text/javascript" src="file.js?abc=123"></script>
Run Code Online (Sandbox Code Playgroud)
var path = document.getElementById('whatever').src;
// ...
Run Code Online (Sandbox Code Playgroud)
有了这个回答,我想表达我的担忧 - 这是一个糟糕的设计决定.为什么要用这种方式包含脚本(使用查询字符串)?如果您正在尝试优化您的站点(通过一个可以为后续页面缓存的大型脚本),这个approch实际上会适得其反,因为浏览器会因为不同的查询而在每个页面上对脚本文件发出新的请求串.正确的方法是在每个页面上有一个大的共享文件,然后是一个小的页面特定的文件.
您可以使用URLapi并document.currentScript检索此`
const url = new URL(document.currentScript.getAttribute('src'));
const scriptParams = Object.fromEntries(url.searchParams)
console.log(scriptParams);
Run Code Online (Sandbox Code Playgroud)