猿问

如何交换标题标签的内容 - HTML/Javascript

我有以下几点:


function changeFirst() {

  let p = document.getElementById("firstElement")[0].innerhtml;

  alert(p);

  if (p = "<h1>This is the 1st element</h1>") {

    document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>"

  } else {

    document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>"

  }

}

<div id="firstElement">

  <h1>This is the 1st element</h1>

</div>


<button onclick="changeFirst()">Change first element</button>

我基本上希望按钮交替firstElementdiv的内容。为什么这不起作用?



天涯尽头无女友
浏览 211回答 3
3回答

ABOUTYOU

document.getElementById 返回一个元素= 也是赋值,你想要 == 或 === 进行比较你可能是这个意思:function changeFirst() {&nbsp; let h = document.querySelector("#firstElement h1");&nbsp; h.textContent = h.textContent==="This is the 1st element" ? "Changed first" : "This is the 1st element"}<div id="firstElement">&nbsp; <h1>This is the 1st element</h1></div><button type="button" onclick="changeFirst()">Change first element</button>

当年话下

像这样尝试。这里我引入了一个标志,并切换到检查内容。var changed = false;function changeFirst() {&nbsp;&nbsp; if (!changed) {&nbsp; &nbsp; changed = true;&nbsp; &nbsp; document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>";&nbsp; } else {&nbsp; &nbsp; changed = false;&nbsp; &nbsp; document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>";&nbsp; }}<div id="firstElement">&nbsp; <h1>This is the 1st element</h1></div><button onclick="changeFirst()">Change first element</button>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答