Calling URL parameters within a .js file

前端 未结 8 2178
北荒
北荒 2021-01-05 01:51

I am calling a .js file within a HTML file. On the URL to the .js file I want to include a parameter that will be accessable to the code INSIDE the .js file.

For exa

8条回答
  •  星月不相逢
    2021-01-05 02:19

    The javascript file by itself is not aware of the URL it's being loaded from.

    What you can do is assign an ID to the script tag you're including in the HTML page, and then grab the SRC attribute through jQuery. By parsing the URL value, you can extract the parameter.

    
    
    var url = $("#widgetJs").attr("src");
    var q = url.split("?")[1];
    if (q) {
        var params = q.split("&");
        etc. etc... 
        i'm not even going to explain further because there are better solutions.
    }
    

    A simpler solution is to declare a global variable in a separate script tag (namespace it to avoid conflicts) and then use it directly in your script.

    Or better yet, have an initialize(param) function in your script that you invoke from the HTML file (this saves you from polluting the global context with unnecessary variables).

提交回复
热议问题