2017-06-02 8 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いますStackOverflowのに' – 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ようこそ(のdocument.getElementById( "tempAppを")のinnerText、10。)!ユニットを気にしない場合は、番号を照合するための最初のオプションを使用する必要があるようです。それでも問題が解決しない場合は、動作しないソースコードを投稿する必要があります。 – styfle

+0

ありがとうございます。それは今働く – Iamlimo

関連する問題