2017-06-03 69 views
0

基本上,我想做的事: 當您按下button#change,在div#board內容必須改變,以無非是:更改HTML內容,然後改回

<h2>Hi!</h2> 
<button type="button" onclick="ChangeAgain();"> 

然後,當您單擊button,它變回它曾經是,那就是:

<h2>Welcome to this page.</h2> 
<p>It's quite boring in here. Why don't you click the button?</p> 
<button onClick="Change();">Button for you to Click</button> 

這裏是我的JavaScript(jQuery的3.2.1),這是行不通的。

$(function() { 
    var inThere = ""; 
    function Change() { 
    inThere += $("#board").html(); 
    $("#board").html("<h2>Hi!</h2> \n 
    <button type=\"button\" onclick=\"ChangeAgain();\">") 
    } 
    function ChangeAgain() { 
    $("#board").html(inThere); 
    } 
}) 
+0

不要包起來文件準備好處理 – Satpal

+0

@你可以詳細解釋答案嗎? –

回答

0

不要在文檔就緒處理程序範圍中定義函數。你一定會得到錯誤,如

"Uncaught ReferenceError: Change is not defined",

var inThere = ""; 
 

 
function Change() { 
 
    inThere += $("#board").html(); 
 
    $("#board").html("<h2>Hi!</h2> \n <button type = \"button\" onclick=\"ChangeAgain();\">Button for you to Click</button>") 
 
} 
 

 
function ChangeAgain() { 
 
    $("#board").html(inThere); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="board"> 
 
    <h2>Welcome to this page.</h2> 
 
    <p>It's quite boring in here. Why don't you click the button?</p> 
 
    <button onClick="Change();">Button for you to Click</button> 
 
</div>

+0

不,它不能在你的代碼片段或我的文件中工作。 –

+1

@AravindSuresh,其工作片段 – Satpal

0

你的功能在全局命名空間,這被認爲是一個很好的做法可用。但由於這個你不應該從你的HTML調用一個函數,但聽你的按鈕的點擊事件代碼:

$(function() { 
 
    var inThere = ""; 
 
    var changed = false; 
 
    var $board = $("#board"); 
 

 
    $board.on("click", "button", function() { 
 
     if (changed) { 
 
      $board.html(inThere); 
 
     } else { 
 
      inThere = $board.html(); 
 
      $board.html("<h2>Hi!</h2><button>Button for you to Click</button>"); 
 
     } 
 

 
     changed = !changed; 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="board"> 
 
    <h2>Welcome to this page.</h2> 
 
    <p>It's quite boring in here. Why don't you click the button?</p> 
 
    <button>Button for you to Click</button> 
 
</div>