简体   繁体   中英

Why is .textContent hidden in Javascript?

Why is .textContent hidden in Javascript even if the if statement says .textContent ? What do I need to add to the code, sothat it is not hidden?

 function F1() { var xmv = ['1', '2']; xm = document.getElementById("xm"); one = document.getElementById("one"); two = document.getElementById("two"); XM = xmv[Math.floor(Math.random() * xmv.length)]; xm.innerHTML = XM; if (xmv === '1') { one.textContent = "one"; } if (xmv === '2') { two.textContent = "two"; } }
 <button onclick="F1()"> New </button> <p> <label id="xm"> </label> <label id="one"> </label> <label id="two"> </label> </p>

This happens because you are comparing an array xmv with string which is always false. You need to compare XM with string instead like:

 function F1() { var xmv = ['1', '2']; xm = document.getElementById("xm"); one = document.getElementById("one"); two = document.getElementById("two"); XM = xmv[Math.floor(Math.random() * xmv.length)]; xm.innerHTML = XM; one.textContent = two.textContent = ''; if (XM === '1') { one.textContent = "one"; } else if (XM === '2') { two.textContent = "two"; } }
 <button onclick="F1()"> New </button> <p> <label id="xm"> </label> <label id="one"> </label> <label id="two"> </label> </p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM