【问题标题】:Special character breaking JavaScript code特殊字符破坏 JavaScript 代码
【发布时间】:2018-06-19 15:39:54
【问题描述】:

我正在为一个机械网站制作一个 JavaScript 闪卡游戏。因为我想把方程式放在卡片上,所以我需要使用 delta(Δ) 符号。

一张卡片可能有:一侧是“功率方程”,另一侧是“P=W/Δt”。如果卡片从第一面开始,它会在按下空格键或按下翻转按钮时翻转。但是,如果它从带有 Δ 符号的第二侧开始,则在按下“翻转”按钮或空格键时它不会翻转。

我尝试过不同的写Δ方式:

Δ Δ Δ

这些都不起作用。 我的代码是:

//Copyright Attribution-ShareAlike 4.0 International 2017 Hazel Meehan


//array containing all options
var options = [ //counts from 0
  "Joules(J)", "Measure of Work",
  "Watts(W)", "Measure of Power",
  "Ek", "Kinetic Energy",
  "Ep", "Potential Energy",
  "Newtons(N)", "Measure of Force",
  "Pascals(Pa)", "Pressure",
  "ms-1", "Metres per Second",
  "ms-2", "Metres per Second Gained",
  "10N", "Value of Gravity",
  "Weight is a", "Force beginning with W",
  "The capacity to do work", "Energy is",
  "d = ΔvΔt is the equation for", "The equation for distance",
  "W=FΔd is the equation for", "The equation for work",
  "P=W/Δt is the equation for", "The equation for power"
];

//initialize variables
var randomNum = 0;
var sideOne = " ";
var sideTwo = " ";

//choose new card using random number
var newCard = function() { //runs on 'next'
  var randomNum = Math.floor(Math.random() * options.length);
  sideOne = options[randomNum];
  if (randomNum % 2 == 0) { //is the number even
    sideTwo = options[randomNum + 1];
  } else {
    sideTwo = options[randomNum - 1];
  }
  document.getElementById("card").innerHTML = sideOne;
};

//show other side of card
var flip = function() { //runs on 'flip'
  if (document.getElementById("card").innerHTML == sideOne) {
    document.getElementById("card").innerHTML = sideTwo;
  } else {
    document.getElementById("card").innerHTML = sideOne;
  }
};

//change card on key down
document.onkeydown = function(e) {
  e = e || window.event;
  if (e.keyCode == '39') { //right arow key
    newCard();
  } else if (e.keyCode == '32') { //space bar
    flip();
  }
}
<article>
  <h2>Flashcards</h2>
  <center><button id="flashButton" onclick="newCard()">Next</button></center>
  <br>
  <center><button id="card"></button></center>
  <br>
  <center><button id="flashButton" onclick="flip()">Flip</button></center>
</article>

【问题讨论】:

  • 它在 SO 上工作,你可能应该在你的 html 中添加一个 &lt;meta charset="utf-8"&gt; 标签才能看到它们。
  • 为我工作。你使用的是什么浏览器?任何登录控制台?
  • 我可以重现该错误,当我将&amp;Delta; 替换为Δ 时它消失了。
  • @MrGeek 这对我不起作用,我尝试添加 但这没有用。我尝试在 IE 中运行它,但它仍然无法正常工作。
  • @ASDFGerte 成功了,谢谢

标签: javascript special-characters


【解决方案1】:

检查元素的innerHtml (if (document.getElementById("card").innerHTML == sideOne)) 时,先前设置的字符串已被解释为 html,在检索它时,&amp;Delta; 现在将是Δ。比较结果为假:

"d = &amp;Delta;v&amp;Delta;t is the equation for" !== "d = ΔvΔt is the equation for"

因此它将innerHtml 再次设置到同一侧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多