2017-06-02 89 views
0
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&#x2103;</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") 
         } 
+0

做'parseInt函数(的document.getElementById( “tempApp”)的innerText,10。)' – Li357

回答

0

的问题是,innerHTML的会转的HTML实体代码实际摄氏度符号。因此,在比较之前将字符串转换为数字(通过parseFloat)可能更容易。

更好的选择是在比较之前将HTML实体转换为字符串。

这里有两个选项:

    // I hard-coded `temp` for this example 
 
        var metric = { 
 
         temp: 300, 
 
         celsius: "&#x2103;", 
 
         fahr: "&#x2109;", 
 
         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&#x2103;</p> 
 
</div>

+0

@lamlimo欢迎计算器!这听起来像你应该使用我的第一个选项来匹配数字,如果你不关心单位。如果你仍然有问题,你应该发布不起作用的源代码。 – styfle

+0

谢谢。它现在有效 – Iamlimo

相关问题