为什么这台仪表不工作?

时间:2016-09-29 17:47:01

标签: javascript jquery html meter

所以我有这段代码(Fiddle):



(function() {
  var meter = document.getElementById('somemeter');
  var Likes = document.getElementById('likes');
  var Dislikes = document.getElementById('dislikes');

  meter.max = Likes.innerHTML + Dislikes.innerHTML;
  meter.value = Likes.innerHTML - Dislikes.innerHTML;
})();

<div id="likes">500</div>
<div id="dislikes">50</div>
<meter value="10" min="0" max="1000" id="somemeter"></meter>
&#13;
&#13;
&#13;

如您所见,Likes.innerHTML500Dislikes.innerHTML 50

出于某种原因,meter.max在我使用Likes.innerHTMLDislikes.innerHTML时无效;但是,当我用meter.max代替50050时,它确实有效。

我做错了吗?

3 个答案:

答案 0 :(得分:3)

您的代码将innerHTML作为字符串。请改用parseInt:

&#13;
&#13;
(function() {
  var meter = document.getElementById('somemeter');
  var Likes = document.getElementById('likes');
  var Dislikes = document.getElementById('dislikes');

  meter.max = parseInt(Likes.innerHTML, 10) + parseInt(Dislikes.innerHTML, 10);
  meter.value = parseInt(Likes.innerHTML, 10) - parseInt(Dislikes.innerHTML, 10);
})();
&#13;
<div id="likes">500</div>
<div id="dislikes">50</div>
<meter value="10" min="0" max="1000" id="somemeter"></meter>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

Javascript检测字符串,您应该使用parseInt值,请尝试以下代码:

&#13;
&#13;
(function() {
  var meter = document.getElementById('somemeter');
  var Likes = document.getElementById('likes');
  var Dislikes = document.getElementById('dislikes');

  meter.max = parseInt(Likes.innerHTML) + parseInt(Dislikes.innerHTML);
  meter.value = parseInt(Likes.innerHTML) - parseInt(Dislikes.innerHTML);
  
  console.log(meter.max)
})();
&#13;
<div id="likes">500</div>
<div id="dislikes">50</div>
<meter value="10" min="0" max="1000" id="somemeter"></meter>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您需要将字符串转换为数值才能使数学工作:

(function() {
  var meter = document.getElementById('somemeter');
  var Likes = document.getElementById('likes');
  var Dislikes = document.getElementById('dislikes');

  meter.max = Number(Likes.innerHTML) + Number(Dislikes.innerHTML);
  meter.value = Number(Likes.innerHTML) - Number(Dislikes.innerHTML);
})();

Fiddle