簡體   English   中英

內容更改后如何使onload腳本再次工作

[英]How to make onload script work again after content changed

我有一個頁面,您可以在其中選擇2張圖片,單擊其中一張時,div的內容就會更改。 新內容還具有2張圖片,單擊它們將加載另一內容。 我正在使用javascript,但是腳本僅加載一次,因此當我到達第二個內容時,它不再更改。

我得到了3個文件:

Main.html-content1.html-content2.html-script.js

main.html中:

<div id="change">
    <div id="rightside">            
        <img src="img.jpg" class="class1" id="water" alt="right choice">
    </div>
    <div id="leftside">
        <img src="img2.jpg" class="class1" id="water2" alt="left choice">
    </div>
</div>
<script type="text/javascript" src="../js/script.js"></script>

以下是將在類更改中替換的內容:content1.html:

<div id="rightside">            
  <img src="img3.jpg" class="class1" id="water3" alt="right choice">
</div>

<div id="leftside">
    <img src="img4.jpg" class="class1" id="water4" alt="left choice">
</div>

這是我要在下次單擊時替換的內容:content2.html:

<div id="rightside">            
  <img src="img5.jpg" class="class1" id="water5" alt="right choice">
</div>

<div id="leftside">
    <img src="img6.jpg" class="class1" id="water6" alt="left choice">
</div>

這是執行此操作的腳本:

window.onload = function() {

    document.getElementById("water").onclick = function() 
    {
        $('#change').load('content1.html');

    };

    document.getElementById("water3").onclick = function() {
        $('#change').load('content2.html');

    };

如果單擊ID為water的圖像,將其替換為content1,然后單擊water3,則沒有任何反應

您可以使用完整的回調來綁定新元素:

window.onload = function() {

    document.getElementById("water").onclick = function() 
    {
        $('#change').load('content1.html', function() {
             document.getElementById("water3").onclick = function() {
                $('#change').load('content2.html');

            };
        });

    };
 };

參考: http//api.jquery.com/load/

暫無
暫無

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

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