将DOM innerHTML值与对象属性进行比较
问题描述:
var metric ={
temp: data.main.temp,
celsius: "℃",
fahr: "℉",
toCelsius: function(){
var convert = this.temp- 273.15;
return Math.ceil(convert) + this.celsius;
},
toFahr: function(){
var convert = (this.temp * 1.8)- 459.67;
return Math.ceil(convert) + this.fahr;
}
}
<div id="temp">
<h2>Temperature</h2>
<p id="tempApp" class="btn btn-default">26℃</p></div>
如何比较$(“#temp”),innerHTML的值和metric.toCelsius值?将DOM innerHTML值与对象属性进行比较
我试着运行下面的代码,但它从来没有工作。
var state1 = metric.toCelsius();
var state2 = metric.toFahr();
var div = document.getElementById("tempApp"
if(div.innerHTML == state1){
console.log("yes")
}
else{
alert("error")
}
答
的问题是,innerHTML的会转的HTML实体代码实际摄氏度符号。因此,在比较之前将字符串转换为数字(通过parseFloat
)可能更容易。
更好的选择是在比较之前将HTML实体转换为字符串。
这里有两个选项:
// I hard-coded `temp` for this example
var metric = {
temp: 300,
celsius: "℃",
fahr: "℉",
toCelsius: function(){
var convert = this.temp - 273.15;
return Math.ceil(convert);
},
toFahr: function(){
var convert = (this.temp * 1.8) - 459.67;
return Math.ceil(convert);
}
};
var div = document.getElementById('tempApp');
console.log('See the innerHTML: ', div.innerHTML);
// Option 1: parse the text and hope for the best
var temp = parseFloat(div.innerHTML);
if (temp === metric.toCelsius()) {
console.log('Matched number!');
} else {
console.log('No match number');
}
// Option 2: convert to a string and compare
var sliced = metric.celsius.slice(3);
var num = parseInt(sliced, 16);
var str = String.fromCharCode(num);
if (div.innerHTML === metric.toCelsius() + str) {
console.log('Matched string!');
} else {
console.log('No match string');
}
<div id="temp">
<h2>Temperature</h2>
<p id="tempApp" class="btn btn-default">27℃</p>
</div>
做'parseInt函数(的document.getElementById( “tempApp”)的innerText,10。)' – Li357