我想要一個按鈕,當點擊它并用其他東西代替時它會消失。下面的代碼會導致單擊按鈕時出現“一些文本”字樣。但這并不是我想要的——如何讓“一些文本”出現在按鈕的位置?
<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>
uj5u.com熱心網友回復:
你可以這樣做:
<button id="MyButton">Click</button>
<script>
document.getElementById("MyButton").addEventListener(
"click",
({ target: button }) => {
button.insertAdjacentText("afterend", "Some text");
button.remove();
},
false
);
</script>
uj5u.com熱心網友回復:
替換this.outerHTML也有效并保持簡單:
<button onclick="this.outerHTML='<p>some text</p>'">Click</button>
uj5u.com熱心網友回復:
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";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470442.html
標籤:javascript html 按钮
下一篇:反應原生:按下時更改組件道具
