简体   繁体   中英

Document ready function not working in nested html page : jQuery

I have a HTML page which having 1 div.

<div id="secondPage"></div>

and having

<script>
$(document).ready(function(){

$("secondPage").load("mySecondHtmlPage.html")
})
</script>

This mySecondHtmlPage.hmtl is loading but I want to have another document ready function in that second html page, which is not firing.

When I have a jQuery reference in that page(second html) too documentReady function is getting fired but it is not loading properly inside the div.

Second html page:

<div>
 My Content  goes here
</div>
<script>
$(document).ready(function(){
alert(''); //Not firing 
})
</script>

When I have a jQuery ref over top that alert is firing but it is not getting loaded in 1st html page.

You can trigger a different event once the page is loaded:

$( "#secondPage" ).load( "mySecondHtmlPage.html", function() {
    $(document).trigger('page-ready');
});

Then use this on the second page:

<div>
     My Content  goes here
</div>
<script>
    $(document).on('page-ready', function(){
        alert(''); //Not firing 
    });
</script>

Read more about .trigger() here .

you should use iframe or XMLHttpRequest

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
       // Action to be performed when the document is read;
    }
};
xhttp.open("GET", "filename", true);
xhttp.send();

在第一页中放置mySecondHtmlPage.html中的所有javascript代码,或者更好地从链接到第一页的体验javascript文件中的两个页面中分离javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM