簡體   English   中英

單擊時用文本/代碼替換 HTML 按鈕

[英]Replace HTML button with text/code when clicked

我想要一個按鈕,當點擊它並用其他東西替換時它會消失。 當點擊按鈕時,下面的代碼會導致“Some text”字樣出現在按鈕下方。 但這不是我想要的——如何讓“一些文本”出現按鈕的位置?

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

替換this.outerHTML也可以並保持簡單:

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

你可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM