jQuery get query string from it's own (self) link

元气小坏坏 提交于 2020-01-04 13:03:35

问题


Is it possible to have a javascript link like this (notice the query string):

  <script type = "text/javascript" src = "/js/myScipt.js?v=3"></script>

and then in myScript.js get the value of v using jQuery? A javascript answer is okay too, but jQuery is preferred. Thanks in advance! I searched all over and all I could find were questions pertaining to getting the value of a query string in the URL, but not from it's own link.


回答1:


//to set script do some thing like this
var version = 3;
document.write('<script type = "text/javascript" src = "/js/myScipt.js?v='+version+'"></script>');
//or 
$("body").append('<script type = "text/javascript" src = "/js/myScipt.js?v='+version+'"></script>');


//to get v from myscript.js
var getV = document.currentScript.src.split("?v=")[1];
// var getV =  $('script').last().attr("src").split("?v=")[1];



回答2:


There is no reason for you to pass information through the link when calling a script. That JavaScript will run after it has been called. There is for sure a better way to do what you are trying to acomplish with this.

Something like this might give you an idea.

 var value;
$("script").each(function(){

var temp = "v=";
If(this.src.indexOf(temp) > -1 )) > -1){

get last digits before "&" if any exist.
And after the index of temp var.
}
});


来源:https://stackoverflow.com/questions/40252285/jquery-get-query-string-from-its-own-self-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!