所以我有这段代码(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;
如您所见,Likes.innerHTML
为500
,Dislikes.innerHTML
为 50
出于某种原因,meter.max
在我使用Likes.innerHTML
或Dislikes.innerHTML
时无效;但是,当我用meter.max
代替500
和50
时,它确实有效。
我做错了吗?
答案 0 :(得分:3)
您的代码将innerHTML
作为字符串。请改用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);
})();
&#13;
<div id="likes">500</div>
<div id="dislikes">50</div>
<meter value="10" min="0" max="1000" id="somemeter"></meter>
&#13;
答案 1 :(得分: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)
})();
&#13;
<div id="likes">500</div>
<div id="dislikes">50</div>
<meter value="10" min="0" max="1000" id="somemeter"></meter>
&#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);
})();