gpt4 book ai didi

javascript - 从里面获取js文件查询参数

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:52:18 25 4
gpt4 key购买 nike

我用这样的查询参数加载这个文件:
<strong>src='somefile.js?userId=123'</strong>

我在读取“userId”查询参数的“somefile.js”文件中编写了以下函数
但我觉得这不是最好的方法。坦率地说,它非常丑陋。 有没有更好的办法

function getId(){
var scripts = document.getElementsByTagName('script'), script;
for(var i in scripts){
if( scripts.hasOwnProperty(i) && scripts[i].src.indexOf('somefile.js') != -1 )
var script = scripts[i];
}

var s = (script.getAttribute.length !== undefined) ?
script.getAttribute('src') :
script.getAttribute('src', 2);

return getQueryParams('userId',s);
};

最佳答案

// extracts the params from the currently running (external) script
var getScriptQp = (function(){
var scripts = document.getElementsByTagName('script');
var this_script_tag = scripts[scripts.length - 1]; //script tag of this file

if( typeof this_script_tag != undefined && this_script_tag.src )
var s = this_script_tag.src;
else{
return this.customer;
}
return s;
})();

// gets the Query Params of a givver query string
function getQueryParam(name, query){
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(query);
if (results == null)
return "";
else
return results[1];
}

getQueryParam( 'param',getScriptQp );

关于javascript - 从里面获取js文件查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1985581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com