2017-06-03 72 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>