How to dynamically include a html file containing javascript

后端 未结 2 582
Happy的楠姐
Happy的楠姐 2021-01-25 19:39

in my website i have a simple navigation bar where clicking on the different items causes the main content to change. Technically, all is done in a single file \"main.html\", wh

相关标签:
2条回答
  • 2021-01-25 20:35

    you are in main.html that contains a head, body. the problem might be that when you load the page your other page also has a head, and body and so on, if you are loading onto a div, it should be only code, can be javascript aswell, but no head or body. but if you resist, here is your solution

    $("#loadnewpagebttn").load(location.href+" foobar ",function(){
        $.getScript("js/yourscript.js"); 
    });
    

    you need to create a script file for that page and load it. inline scripts are some what of a bad habit anyways

    full example:

    jQuery.getScript( url, [ success(data, textStatus) ] )
    url - A string containing the URL to which the request is sent.
    
    success(data, textStatus) - A callback function that is executed if the request succeeds.
    
    $.getScript('ajax/test.js', function() {
      alert('Load was performed.');
    });
    

    http://api.jquery.com/jQuery.getScript/

    0 讨论(0)
  • 2021-01-25 20:38

    You can trigger a custom event to notify your other.html script that the tree is loaded. I haven't tried it, but I would use something like that :

    In main.html:

    $('#div_to_load').load('other.html',{},function(){
        $('#div_to_load').trigger('loaded')
    })
    

    In other.html

    $('#div_to_load').on('loaded', function(){
         // Code to execute  
    })
    

    I don't know if that could do the trick.

    Edit : I asume that the javascript directly included in your other.html is executed anyway.

    0 讨论(0)
提交回复
热议问题