The example in this article describes the Jquery+ajax implementation of a dynamic script execution method. Share to everyone for your reference. The specific analysis is as follows:
Sometimes it is not necessary to get all the JavaScript you need when the page is first loaded. The specific script needs to be taken, depending on the user's operation. While it is possible to make <script> tags dynamically when needed, the more elegant way to note people's required code is to load the. js file directly through Jqueiy.
It is as simple as loading an HTML fragment to inject a human script into the page. In this case, however, you need to use the global function $.getscript (), a global function similar to its sibling function, to accept a URL parameter to find the script file, see the following code:
Copy Code code as follows:
$ (document). Ready (function () {
$ (' #letter-C-A '). Click (Function (event) {Event.preventdefault ();
$.getscript (' c.js ');
});
});
In the previous example, the next step should be to process the result data so that the loaded file can be used efficiently. However, for a script file, the process is automated; in other words, the script executes automatically.
Scripts obtained in this manner are executed in the global context of the current page. This means that the script has access to the functions and variables defined in the global environment, including jquery itself, of course. Thus, we can mimic the JSON example to prepare the script code to insert the HTML into the page as the script executes. Now save the following scripting code in C.js:
Copy Code code as follows:
var entries = [
{
"term": "Calamity",
"Part": "N.",
"Definition": "A more than commonly plain and ...
},
{
"term": "Cannibal",
"Part": "N.",
"Definition": "A gastronome of the old school ..."
},
{
"term": "Childhood",
"Part": "N.",
"Definition": "The period of human life intermediate ..."
}
Omitted content
];
var html = ';
$.each (entries, function () {
html + + ' <div class= ' entry ' > ';
html + + '
html + + ' <div class= ' part ' > ' + this.part + ' </div> ';
html + + ' <div class= ' definition ' > ' + this.definition + ' </div> ';
HTML + = ' </div> ';
});
$ (' #dictionary '). HTML (HTML);
Finally, click the C link and you should see the results we expected.
I hope this article will help you with your jquery programming.