【问题标题】:HTML onclick handler not triggering innerHTML changesHTML onclick 处理程序未触发 innerHTML 更改
【发布时间】:2014-07-31 14:26:11
【问题描述】:

我正在制作饥饿游戏模拟,这是我的代码:

console.log(data);
document.getElementById("playarea").innerHTML = data;
console.log(document.getElementById("playarea").innerHTML);

当我将变量 data 记录到控制台时,它会给出以下结果,

<img src='img/fight.png'><br />
You grabbed a loaf of bread out of the crate, the girl from 9 comes to you for a fight.
<br />
<button onclick=fight('You grabbed a loaf of bread out of the crate, the girl from 9 
comes to you for a fight.','','',4,1,2)>
Punch in the head
</button><br />
<button onclick=fight('You grabbed a loaf of bread out of the crate, the girl from 9 
comes to you for a fight.','','',4,1,2)>Punch in the chest</button><br />

当我记录 innerHTMLplayarea 时,我得到了

<img src="img/fight.png"><br>
You grabbed a loaf of bread out of the crate, the girl from 9 comes to you for a fight.
<br>
<button onclick="fight('You" grabbed="" a="" loaf="" of="" bread="" out="" the=""  
crate,="" girl="" from="" 9="" comes="" to="" you="" for="" 
fight.','','',4,1,2)="">
Punch in the head
</button><br>
<button onclick="fight('You" grabbed="" a="" loaf="" of="" bread="" out="" the="" 
crate,="" girl="" from="" 9="" comes="" to="" you="" for=""    
fight.','','',4,1,2)="">
Punch in the chest
</button><br>

onclick 中,它分隔每个单词并将它们视为变量。

如何使innerHTML 与数据变量相同?

【问题讨论】:

  • 最好用jQuery,忘记引号问题。 $("#playarea").html(数据)

标签: javascript html onclick innerhtml


【解决方案1】:

变化(数据内)

<button onclick=fight('You grabbed ...','','',4,1,2)>

进入

<button onclick="fight('You grabbed ...','','',4,1,2)">

如果值只有一个单词,则只能省略引号。

【讨论】:

  • +1;这就是答案。为了详细说明这一点,当您省略引号时,额外的单词被解析为&lt;button&gt; 的属性,因此grabbed="" a="" 等。
  • 谢谢,现在可以正常使用了。我必须在字符串中使用两种类型的引号,所以我在 data 变量中添加了 + ' " ' + 并且效果很好!
猜你喜欢
  • 1970-01-01
  • 2015-11-08
  • 2015-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-26
相关资源
最近更新 更多