views:

628

answers:

4

Hi,

I'm trying to reference some javascript files in a remotely loaded (injected) HTML file via jQuery's .load() function. The javascript files I'm attempting to utilize in the loaded HTML file are already included in the loaded HTML's parent HTML page.

Initially, I thought that making references to these files in the loaded HTML would work fine since it is included on the page, however it doesn't seem to work.

Can anyone tell me how I can use javascript with my injected HTML file?

+1  A: 

If I understand correctly, it sounds like you need to be using getScript() - This loads and executes, a local JavaScript file using an HTTP GET request.

$.getScript( url, [callback] )
Russ Cam
A: 

If the script element is part of your loaded html then you can just append it to the body and it will work.

Example:

$.ajax({
    //...
    //...
    success: function(response) {
        // assuming response is a full HTML page
        var r = $(response);
        // append your content
        $("#someContainer").append($("#someContent", r));
        // append the scripts
        $("body").append($("script", r));
    }
    //...
    //...
});

of course you can use your own selectors, this is just an example. Let me know how that works out for you.

Darko Z
A: 
  1. If test1.htm contains :

    $(document).ready(function() { $('.main').load('test2.htm', function() { $('.result').text('page has been retrieved'); }); });

  2. and test2.html contains : < script type="text/javascript" src="exscript.js">< / script >

in the head of the document.

  1. exscript.js contains :

    alert('hi');

the if you load test1.htm you'll be alerted hi. goodbye! :)

Ali
A: 

I believe what you're looking for is .live()

.live() allows you to "attach a handler to the event for all elements which match the current selector, now or in the future."

For instance:

$(".clickme").click(function(){
  $(this).fadeOut();
}

This code will not work on any element that has been injected into the page with .load() or .get()

But if you do this:

$(".clickme").live('click', function(){
  $(this).fadeOut();
}

...it will work even on elements that have been injected into the page layout via javascript.

More info at jQuery AP

motorfirebox