简体   繁体   English

Javascript如何比较两个字符串

[英]Javascript how to compare two strings

This is the Javascript Function. 这是Javascript函数。 Please Explain How to compare two string in Javascript. 请说明如何比较Javascript中的两个字符串。

   <head>
    <script type="text/javascript">
/*javascript function*/ 
    function ajax(str)
    {
    if (str.length==0)
      {
      document.getElementById("res").innerHTML="";    
      return;
      }
      if(str=="Select City")
      {
      alert("Please Select a City");
      }
    document.getElementById("res").innerHTML=="";
    var url="code1.php?q="+str+"&r"+Math.random();
    var obj;
    try{
    obj=new ActiveXObject(Microsoft.XMLHTTP);
    }
    catch(e)
    {
        try
        {
        obj=new XMLHttpRequest();
        }
        catch(e)
        {
        alert("Your browser not suport ajax");
        }
    }
    obj.open('Get',url,true);
    obj.send(null);
    obj.onreadystatechange=function()
    {
    if(obj.readyState==4)
    {
    document.getElementById("res").innerHTML=obj.responseText;
    }
    }
    }
    </script>
    </head>

    <body>

    <select onchange="ajax(this.value)" name="sel" id="btn"><option>Dharmashala</option><option>Manali</option><option>Shimla</option></select>
    <div id="res"></div>
    </body>
    </html>

But it does not work please suggest me a proper method to do this. 但这是行不通的,请向我建议一种执行此操作的正确方法。

=== for string comparison ===用于字符串比较

if(str === "Select City") {
    alert("Please Select a City");`
}

How to compare strings in JavaScript? 如何比较JavaScript中的字符串? Use the == operator for equivalence and > / < for alphabetical difference. 使用==运算符表示等价,并使用> / <表示字母差异。

In your code, this line seems to be a bit useless: 在您的代码中,这一行似乎没有用:

document.getElementById("res").innerHTML=="";

Don't you want an assignment here ( = )? 您不想在这里分配作业( = )吗?

I'm pretty sure it's not working because you have your this context incorrect. 我敢肯定,它不工作,因为你有你的this方面不正确。 this.value is trying to call the value of your select element instead of the selected option . this.value试图调用select元素的value而不是selected option Try this: 尝试这个:

window.addEventListener('load', function(){
  var select = document.getElementById('btn');
  var selected = select.options[select.selectedIndex].value;
}, false);
window.addEventListener('change', function(selected) { changeHandler(selected); }, false);

function changeHandler(selected) {
  // run your ajax() function
}

Also, be sure to put a value on each of your option elements. 另外,请确保在每个option元素上都赋一个value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM