In a onclick
attribute, this
represents the target element (of the event), so it is not window
, but the clicked span
.
So you could do just this.innerHTML = 2+4
, ...etc. In fact, I would prefer using this.textContent
here, as you don't plan to inject HTML encoding, but plain text.
BTW: no eval
is needed.
<p>2 + 4 = <span onclick='this.textContent = 2+4'>답</span></p>
<p>4 * 20 + 64 = <span onclick='this.textContent = 4*20+64'>답</span></p>
<p>20 / 5 - 8 * 2 = <span onclick='this.textContent = 20/5 - 8*2'>답</span></p>
And to make it more dynamic, you could use eval
, so that you don't need to repeat the formula:
document.addEventListener("click", function(e) {
if (e.target.className == "calc") {
let formula = e.target.parentNode.textContent.split("=")[0];
e.target.textContent = eval(formula);
}
});
<p>2 + 4 = <span class="calc">답</span></p>
<p>4 * 20 + 64 = <span class="calc">답</span></p>
<p>20 / 5 - 8 * 2 = <span class="calc">답</span></p>
Note that the JavaScript in this case needs to be in script
tag.