【问题标题】:Change HTML Content using jQuery 3, then change it back使用 jQuery 3 更改 HTML 内容,然后将其更改回来
【发布时间】:2017-06-03 23:04:59
【问题描述】:

基本上,我想做的是: 当你按下button#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>

这是我的 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);
  }
})

【问题讨论】:

  • 不要将它们包装在文档就绪处理程序中
  • @Satpal 你能详细说明一下答案吗?

标签: javascript jquery html dom-manipulation


【解决方案1】:

不要在文档就绪处理程序范围内定义函数。您一定会遇到类似的错误

"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>

【讨论】:

  • 不,它在您的 sn-p 或我的文件中不起作用。
【解决方案2】:

您的函数在全局命名空间中不可用,这被认为是一个好习惯。但是由于这个原因,你不应该从你的 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>

【讨论】:

    猜你喜欢
    • 2013-04-23
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 2013-03-02
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    相关资源
    最近更新 更多