jquery getting GET variables from javascript file

2019-08-01 11:46发布

I have a link, and when a user clicks it, it pushes a javascript file onto the page. in addition to that, it adds on parameters to the javascript src example:

<script type="text/javascript" src="javascripfile.js?r=some%values&u=more&values">

This isn't getting passed through URL on browser. I was wondering how I would get these parameters inside javascriptfile.js?

javascriptfile.js:

(function(){
     //how to get r value, u value?
}());

Thanks for your help!

1条回答
Root(大扎)
2楼-- · 2019-08-01 12:09

Please try this: http://jsfiddle.net/9Mvxb/ or http://jsfiddle.net/mKNPT/1/ And http://jsfiddle.net/mKNPT/3/

Please note if you are not comfortable using class see this Demo: http://jsfiddle.net/24UdH/

API: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf

further in case you wondering about val.indexOf("?") + 1 why +1 it is to avid ?

This should help, :)

code

$("script").each(function(){
   if ($(this).prop('src').split("?")[0].indexOf("javascripfile.js") )
          value = $(this).prop("src");
});

var returnStr = value.substr(value.indexOf("?") +1);

alert(" value after ? is ==> " + returnStr);

var spliMe = returnStr.split('&');

alert("value of R ==> " + spliMe[0]);

OR

    var value = $(".foo").prop("src");

    var returnStr = value.substr(value.indexOf("?") +1);

    alert(" value after ? is ==> " + returnStr);

    var spliMe = returnStr.split('&');

​

tag

<script type="text/javascript" class="foo" src="javascripfile.js?r=some%values&u=more&values">
查看更多
登录 后发表回答