1

所以我有这个代码(小提琴):

(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>

如您所见,Likes.innerHTMLis500Dislikes.innerHTMLis 50

出于某种原因,当我使用or时;meter.max不起作用 但是,当我用for和替换它们时,它确实有效。Likes.innerHTMLDislikes.innerHTMLmeter.max50050

难道我做错了什么?

4

3 回答 3

3

您的代码采用innerHTMLas 字符串。改用 parseInt:

(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);
})();
<div id="likes">500</div>
<div id="dislikes">50</div>
<meter value="10" min="0" max="1000" id="somemeter"></meter>

于 2016-09-29T17:52:43.913 回答
2

Javascript 检测字符串,你应该使用parseInt值,试试这个代码:

(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)
})();
<div id="likes">500</div>
<div id="dislikes">50</div>
<meter value="10" min="0" max="1000" id="somemeter"></meter>

于 2016-09-29T17:52:46.960 回答
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);
})();

小提琴

于 2016-09-29T17:55:07.490 回答