簡體   English   中英

如何將已加載的JavaScript和CSS應用於.load()內容?

[英]How do I apply loaded javascript and css to .load() content?

我正在使用jquery .load()加載.html內容,但是在通過.load()函數加載后,javascript和css不會應用於one.html / two.html。

下面的例子:

<head>
    <style> styles1 </style>
    <link href="stylesheets/style2.css" rel="stylesheet">
    <script src="script1.js">
    <script>     
        $(document).ready(function(){
           $("button.os").click(function(){
              fillmein = $(this).attr("target");
              fillmeinfile = $(this).attr("target")+'.html';
              $("."+fillmein).load("/contentfolder/"+fillmeinfile);
           });
        });

     ...
     other scripts
     ...
    </script>
</head>

<body>
   <p>the css and any js is applied to this block</p>
   <button class="os" target="one">replace</button>
   <div class="one">I will be replaced by one.html</div>
   <button class="os" target="two">replace</button>
   <div class="two">I will be replaced by two.html</div>
</body>

我了解到,one.html / two.html是在瀏覽器加載樣式和javascript之后加載的,但是我如何獲取<head>的樣式和javascript應用於新加載的one.html / two。 HTML?

我是jQuery的新手,所以讓我知道如何根據需要進行說明。 謝謝!

編輯感謝您為大家提供答案! 更新了代碼示例以闡明我的意思。

<style><script>復制到one.html和two.html可以,但是如果我兩次加載JavaScript,則可能會發生沖突。 例如,具有搜索$(document)的邏輯以及折疊和擴展部分的功能可以多次調用。 是否可以使主頁中加載的js和css在新加載的.html文件上工作,或者是否有任何干凈且干燥的方法來做到這一點?

正如Arun P Johny在評論中所建議的那樣

您只需將CSS內聯在目標文檔上,它將隨內容一起自動加載。

你可以寫

$('button').on('click','Classname',function(){
  //write your structure here
  })

這將適用於所有帶有'Classname'標簽,這些標簽已經存在或以后會動態添加。

暫無
暫無

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

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