【问题标题】:Selected option alert in jqueryjquery中的选定选项警报
【发布时间】:2025-12-17 06:20:03
【问题描述】:
我正在尝试根据所选选项在网页中发出警报。
但它不起作用。
我试过了:
$(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>
【问题讨论】:
标签:
javascript
jquery
html
drop-down-menu
【解决方案1】:
你有很多语法错误:
-
if 或 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");
}
});
});
<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】:
$(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>
【解决方案3】:
您的语法无效。这不是if 或if 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(条件)语句
其他 声明
所以你可以有任何预期的声明。
if (true) foo();
else switch (x) {
case 'y': bar();
}