我在學習JavaScript。 我正在嘗試使用replaceChild()
方法在頁面上切換文本。我想出了下面的代碼。我不明白爲什麼它不起作用。請幫助。用JavaScript切換文字
<html>
<head>
<script>
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1");
var l8 = document.createElement("h1").innerHTML="After";
var l88 = document.createElement("h1").innerHTML="Before";
if (b4[0].innerHTML=="Before"){
be.replaceChild(l8,b4[0])
}
if (b4[0].innerHTML=="After") {
be.replaceChild(l88,b4[0]);
}
}
</script>
</head>
<body>
<div id="main" onclick="toggleText()">
<h1>Before</h1>
</div>
</body>
</html>
@kapa有編輯:) –
旁註一個選項。如果(b4 [0] .innerHTML ==「之後出現''''''''''''後面'實際元素 – j08691
getElementsByTagName(」h1「)[0]我使用它的時候我覺得合適,謝謝:)。 – mplungjan