HTML onclick()帮助,图像和段落在一起



我希望这是相对简单的修复。我不确定我做错了什么。我想要HTML中的一个按钮来显示一个段落,然后用第二个按钮来组合一个段落和一个图像。它在除法器下面吐出结果,并预先在下面显示一个默认值。看到一些例子后,这个部分开始工作了。我还用它来组合文本,所以这看起来很好,但当我尝试粘贴图像时,我一无所获。不确定我做错了什么。我得到的是:

<!DOCTYPE html>
<html>
<body>
<p>
Filler text here.
</p>
<input type="button" value="Test 1"
onclick="document.getElementById('outputDiv').innerHTML=
'Testing words.';">
<input type="button" value="Test 2"
onclick="document.getElementById('outputDiv').innerHTML=
'Testing combining words ' +
'and images.' +
'<img src="https://lh3.googleusercontent.com/proxy/afg90RRXB-Ah7-9IZZU-uj9iPztl4Y6gDUAtR-02O5jNIcTll2XlDJdXd3AZKtAlRPcBZ_2iZiGJhRvko-k2GOd9FSFuNYw" alt="W3Schools.com">';">
<hr>
<div id="outputDiv">
Testing output.
</div>
</body>
</html>

onclick属性中使用&quot;而不是"

<p>
Filler text here.
</p>
<input type="button" value="Test 1"
onclick="document.getElementById('outputDiv').innerHTML=
'Testing words.';">
<input type="button" value="Test 2"
onclick="document.getElementById('outputDiv').innerHTML=
'Testing combining words ' +
'and images.' +
'<img src=&quot;https://lh3.googleusercontent.com/proxy/afg90RRXB-Ah7-9IZZU-uj9iPztl4Y6gDUAtR-02O5jNIcTll2XlDJdXd3AZKtAlRPcBZ_2iZiGJhRvko-k2GOd9FSFuNYw&quot; alt=&quot;W3Schools.com&quot;>';">
<hr>
<div id="outputDiv">
Testing output.
</div>

但这真的很难看。改为使用JavaScript附加事件侦听器怎么样?

const [btn1, btn2] = document.querySelectorAll('input');
const outputDiv = document.getElementById('outputDiv');
btn1.onclick = () => outputDiv.innerHTML = 'Testing words.';
btn2.onclick = () => outputDiv.innerHTML = 'Testing combining words and images.' +
'<img src="https://lh3.googleusercontent.com/proxy/afg90RRXB-Ah7-9IZZU-uj9iPztl4Y6gDUAtR-02O5jNIcTll2XlDJdXd3AZKtAlRPcBZ_2iZiGJhRvko-k2GOd9FSFuNYw" alt="W3Schools.com">';
<p>
Filler text here.
</p>
<input type="button" value="Test 1">
<input type="button" value="Test 2"">
<hr>
<div id="outputDiv">
Testing output.
</div>

我强烈建议尽可能避免使用内联处理程序——所需的转义和它们疯狂的作用域链使代码的读写比实际需要的要困难得多

最新更新