在jquery中选择选项警报

时间:2017-09-23 16:49:43

标签: javascript jquery html drop-down-menu

我正在尝试根据所选的选项在网页中提醒。

但它没有用。

我试过了:



$(document).ready(function(){
    $("select.country").change(function(){
        var selectedCountry = $(".country option:selected").text();
        if{
         selectedCountry == "India"   ;
            alert("You have selected the language - Hindi");
        }
        elseif{
            selectedCountry == "Nepal";
            alert("You have selected the language - Nepali");
        }
        
    });
});

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
        <label>Select Country:</label>
        <select class="country">
            <option value="nepal">Nepal</option>
            <option value="india">India</option>
        </select>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

你有很多语法错误:

  • #aboutif语句的条件在语句之后,在括号内。
  • else-if语句为else if而非else if

这是一个修复:

elseif
$(document).ready(function() {
  $("select.country").change(function() {
    var selectedCountry = $(".country option:selected").text();
    if (selectedCountry == "India") {
      alert("You have selected the language - Hindi");
    } else if (selectedCountry == "Nepal") {
      alert("You have selected the language - Nepali");
    }
  });
});

答案 1 :(得分:0)

$(document).ready(function(){
    $("select.country").change(function(){
        var selectedCountry = $(".country option:selected").text();
        if(selectedCountry == "India" ){
            alert("You have selected the language - Hindi");
        }
        else if(selectedCountry == "Nepal"){
            alert("You have selected the language - Nepali");
        }
        
    });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
        <label>Select Country:</label>
        <select class="country">
            <option value="nepal">Nepal</option>
            <option value="india">India</option>
        </select>

答案 2 :(得分:0)

您的语法无效。这不是ifif else语句的结构。

这是重写:

$(document).ready(function() {
  $("select.country").change(function() {
    var selectedCountry = $(".country option:selected").text();

    // The condition must be in parens, and before the `{`
    if (selectedCountry == "India") {
      alert("You have selected the language - Hindi");
      
    // Here as well, and `else if` is two words
    } else if (selectedCountry == "Nepal") {
      alert("You have selected the language - Nepali");
    }
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<label>Select Country:</label>
<select class="country">
            <option value="nepal">Nepal</option>
            <option value="india">India</option>
        </select>

更确切地说,本身没有else if声明。它只是一个else,另一个if语句作为要执行的语句提供。

语法类似于:

  

如果(条件)声明   
其他 声明

所以你可以有任何预期的陈述。

if (true) foo();
else switch (x) {
  case 'y': bar();
}