试图比较2字符串if语句[关闭]

问题描述:

I am trying to compare 2 strings, but there are not comparing as I would like. I am getting a value from a div and converting it to a string, when I find the typeof it is telling me is a string but still it is passing by the if statement.

When I write.document they both look the same. Thanks

<div id="countries"><?php $geoplugin->locate(); echo"{$geoplugin->countryName}"?> </div> 

<script>
                 var country = document.getElementById("countries");
                 var count = country.innerHTML;
                 var newc = String(count);


                 if ( newc === "Ireland" ){
                    document.write("this is ireland");
                    alert("You are from Ireland");

                 }else{
                    document.write("You Live in " + newc);
                                    //alert(typeof newc);                  
                    //alert(newc);

                 }

                 </script>

我正在尝试比较2个字符串,但没有按照我的意愿进行比较。 我从div获取一个值并将其转换为字符串,当我发现它的类型告诉我是一个字符串但仍然通过if语句。 p>

当我写.document时,它们看起来都一样。 谢谢 p>

 &lt; div id =“countries”&gt;&lt;  ?php $ geoplugin-&gt; locate(); 回声 “{$ geoplugin-&GT;国家名称}” &GT?;  &LT; / DIV&GT;  
 
&lt; script&gt; 
 var country = document.getElementById(“countries”); 
 var count = country.innerHTML; 
 var newc = String(count); 
 
 
 if(newc =  ==“爱尔兰”){
 document.write(“这是爱尔兰”); 
提醒(“你来自爱尔兰”); 
 
}其他{
 document.write(“你住在”)  + newc); 
 // alert(typeof newc);  
 //警告(newc); 
 
} 
 
&lt; / script&gt; 
  code>  pre> 
  div>

From your HTML it looks like you've got a trailing space after the <?php ...> instruction. So whatever is there, it won't exactly equal "Ireland". Try using trim to remove any whitespace from the ends of your string.

var newc = String(count).trim();