Pass value from page to js

Source: Internet
Author: User

Js Code
$ (Function (){
// Obtain parameters from the page
Var getArgs = (function (){
Var SC = document. getElementsByTagName ('script ');
Var paramsArr = SC [SC. length-1]. src. split ('? ') [1]. split ('&');
Var args ={}, argsStr = [], param, t, name, value;
For (var I = 0, len = paramsArr. length; I <len; I ++ ){
Param = paramsArr [I]. split ('= ');
Name = param [0], value = param [1];
If (typeof args [name] = "undefined") {// The parameter does not exist
Args [name] = value;
} Else if (typeof args [name] = "string") {// if the parameter already exists, it is saved as an array.
Args [name] = [args [name]
Args [name]. push (value );
} Else {// already an array
Args [name]. push (value );
}
}
/* The showArg and args. toString values in the actual application can be deleted. This is only to test the content returned by the getArgs function */
Var showArg = function (x) {// convert the display mode of different data
If (typeof (x) = "string "&&! /\ D +/. test (x ))
Return "'" + x + "'"; // string
If (x instanceof Array)
Return "[" + x + "]" // Array
Return x; // number
}
// Assemble it into json format
Args. toString = function (){
For (var I in args)
ArgsStr. push (I + ':' + showArg (args [I]);
Return '{' + argsStr. join (',') + '}';
}
Return function (){
Return args;
} // Return all obtained parameters in json format
})();
});
With this method, you can pass parameters to js from the page.
 
Html code
<Script src = ".../example. js? Id = 1 "type =" text/javascript "> </script>
For example, if you reference example. js on the page and pass the id with the parameter equal to 1, you can use getArgs () [id] In example. js to get the id value.

Author "fresh-daily"
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.