$.getScript of Jquery's ajax methods can be used to load and execute javascript from remote locatio开发者_如何学编程n... Can it also be used to just load the javascript and execute it later when some event occurs on elements that have been loaded using ajax based on some user action...?
Thanks and Regards....
$.getScript
will load and execute Javascript. If you want to just load the Javascript, you will have to put the Javascript in a function, and then execute that function when a future event occurs.
suppose you call:
$.getScript('http://example.com/hello.js');
and it contains the following:
function Hello() {
alert('hello');
}
The Javascript will be executed, but since the alert is in the function it won't be ran. It won't run until you call the function Hello()
. So for the second part, suppose you want to wire it so that when a link is clicked the Hello()
function runs. You can provide a callback to run after the Javascript is loaded. So you could do this:
$.getScript('http://example.com/hello.js', function() { Hello(); });
After the script is loaded, that will set a click event handler on your links which will call the Hello
function.
Is the goal to have the script bind to the elements that have not yet loaded or to lower the number of calls to the remote script?
If it's the first, you don't need to save the script for later executions, you simply need to put the $.getScript()
into another function, and bind the events you want to that function:
function executeScript() {
$.getScript("somescript.js",
blah blah blah
);
}
$(".post_loaded_elements").hover(executeScript);
However, if the script is on some remote server and you don't want to make a remote call every time a user hovers over an element, you probably need to use some sort of serialization method, where you would request the contents of the script using another ajax method, and de-serialize it and run it. This would use the same setup as the above, only with an extra step of retrieving the script and serializing it into a variable that gets de-serialized in the function. I'll do a quick check to see if serialization is fairly simply in jquery.
Yes, this is possible. I made the following script, it is composed of three files, the interface, an html textbox that is loaded from an external file when the users clicks button 2, and an external script that is loaded when the users clicks the first button and alerts the value of the textbox, which was loaded before the script but after the document loaded.
Click button 2, type something in the textbox and then click button 1, here is the code.
html page (interface)
<button id="b1">button 1</button>
<button id="b2">button 2</button>
jquery
$(document).ready(function(){
$("#b1").click(function(){
$.getScript('externalscript.js');
});
$("#b2").click(function(){
$("#load").load('test.html');
});
});
Loaded element
<input type="text" id="text" />
external script
alert($("#text").val());
精彩评论