簡體   English   中英

在另一個HTML文件和JS中包括一個HTML文件

[英]including an html file in another html file and JS

假設我有兩個html文件,one.html和two.html。 我想在one.html中包含two.html,所以我已經這樣做了,

<script>
        $(function(){
            $("#middle").load("two.html");
        });
</script>

我有一個腳本文件,說是script.js,我在one.html末尾加載為

<script src="scripts/script.js" ></script>

在該文件中,我正在編寫要在two.html元素上實現的功能。 但是這些功能未應用在two.html上。 那么,這樣做的正確方法是什么?

使用$.get jQuery函數

$.get( "tow.html", function( data ) {
  $( "#middle" ).html( data );
  alert( "Load was performed." );
});

您為什么不使用(隱藏的) iframe 如果它位於同一服務器上,則可以訪問父頁面(one.html)的功能和元素:

window.parent.example_function();

或使用其DOM元素。

要在動態加載的元素上添加事件,您需要在jquery <1.9中使用.live()函數;如果jquery> = 1.9,則需要使用.on()

。生活()

。上()

你可以先加載頁面的第二內容和包括被列入額外的HTML 后才的JavaScript。

$.get("two.html", function(data) {
    $('#middle').html(data);
    $('head').append($('<script>').attr('type', 'text/javascript').attr('src', 'scripts/script.js'));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM