单击时,用文本/代码替换HTML按钮

发布于 2025-01-25 22:05:55 字数 503 浏览 2 评论 0原文

我想在单击并用其他东西替换时有一个按钮消失的按钮。下面的代码会导致“某些文本”单词单击时出现在按钮下方。那不是我想要的 - 如何获得“一些文本”来代替按钮?

<button id="MyButton">Click</button>

<script>
    function addListener() {
        document.getElementById("MyButton").addEventListener("click", ReplaceButton, false)
    }

    addListener()

    function ReplaceButton() {
        node = document.getElementById("MyButton")
        node.insertAdjacentHTML("afterend", "<p>Some text</p>") 
    }
</script>

I would like to have a button that disappears when clicked on and replaced with something else. The code below causes the words "Some text" to appear below the button when it's clicked on. That's not quite what I want though -- how do I get "Some text" to appear in place of the button?

<button id="MyButton">Click</button>

<script>
    function addListener() {
        document.getElementById("MyButton").addEventListener("click", ReplaceButton, false)
    }

    addListener()

    function ReplaceButton() {
        node = document.getElementById("MyButton")
        node.insertAdjacentHTML("afterend", "<p>Some text</p>") 
    }
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

把昨日还给我 2025-02-01 22:05:55

替换this.outerhtml也可以工作并保持简单:

<button onclick="this.outerHTML='<p>some text</p>'">Click</button>

Replacing this.outerHTML also works and keeps it simple:

<button onclick="this.outerHTML='<p>some text</p>'">Click</button>

↘人皮目录ツ 2025-02-01 22:05:55

您可以做这样的事情:

<button id="MyButton">Click</button>
<script>
   document.getElementById("MyButton").addEventListener(
      "click",
      ({ target: button }) => {
        button.insertAdjacentText("afterend", "Some text");
        button.remove();
      },
      false
   );
</script>

You can do something like this :

<button id="MyButton">Click</button>
<script>
   document.getElementById("MyButton").addEventListener(
      "click",
      ({ target: button }) => {
        button.insertAdjacentText("afterend", "Some text");
        button.remove();
      },
      false
   );
</script>
来世叙缘 2025-02-01 22:05:55
function ReplaceButton() {
    // Get the button
    node = document.getElementById("MyButton");
    // Add some HTML after the button (in the buttons parent)
    node.insertAdjacentHTML("afterend", "<p>Some text</p>");
    // Hide the button, optionally remove from tree with `node.remove()`
    node.style.display = "none";
}
function ReplaceButton() {
    // Get the button
    node = document.getElementById("MyButton");
    // Add some HTML after the button (in the buttons parent)
    node.insertAdjacentHTML("afterend", "<p>Some text</p>");
    // Hide the button, optionally remove from tree with `node.remove()`
    node.style.display = "none";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文