使用jQuery 3更改HTML内容,然后将其更改回来

时间:2017-06-03 14:44:36

标签: javascript jquery html dom-manipulation

基本上,我想做的事情: 当您按#change div时,#board <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> 时,它必须改回原来的状态,即:

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

这是我的JavaScript(jQuery 3.2.1),它无效。

{{1}}

2 个答案:

答案 0 :(得分:0)

不要在文档就绪处理程序范围中定义该函数。你必须得到像

这样的错误
  

“未捕获的ReferenceError:未定义更改”,

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>

答案 1 :(得分:0)

您的功能在全局命名空间中不可用,这被认为是一种很好的做法。但由于这个原因,你不应该从你的HTML中调用一个函数,而是在你的代码中听按钮的click事件:

$(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>