我有一个选择框,有两个选项作为最近和流行,要求是,如果我选择最近然后调用后端应该去获得相应的响应,同样应该发生流行也是如此。我在这里问了很多问题,但找不到我要找的确切答案。我目前的代码看起来像这样
<select class="recentOrPopular" name="mostpopular">
<option value="recent">Recent</option>
<option value="popular">Popular</option>
</select>
这是简单的html,有两个选项,JavaScript是:
if($('.recentOrPopular').val('recent')){
this.myrecentFunction();
}
$( ".recentOrPopular" ).change(function() {
if($('.recentOrPopular').val('popular')){
this.myPopularFunction();
}
if($('.recentOrPopular').val('recent')){
this.myrecentFunction();
}
});
所以默认情况下,myrecentFunction最初会被调用,但是如果我正在更改该选项,那么两个if块都会被调用。与小提琴相关的链接是:here
答案 0 :(得分:2)
您使用.val(value)设置值而不是比较
$(".recentOrPopular").change(function () {
var value = $(this).val();
if (value == 'popular') {
this.myPopularFunction();
} else if (value == 'recent') {
this.myrecentFunction();
}
});
使用开关
$(".recentOrPopular").change(function () {
var value = $(this).val();
switch (value) {
case 'popular':
this.myPopularFunction();
break;
case 'recent':
this.myrecentFunction();
break;
}
});
答案 1 :(得分:2)
$('.recentOrPopular').val('popular')
用于设置值,如果要比较它们使用
if($('.recentOrPopular').val() == 'popular')
同样,不要使用if()然后if()使用if ... else if()这样可以确保如果第一个条件满足,则第二个条件不会执行。
答案 2 :(得分:0)
将代码修改为
$( ".recentOrPopular" ).change(function() {
if($('.recentOrPopular').val()=='popular'){
this.myPopularFunction();
}
if($('.recentOrPopular').val()=='recent'){
this.myrecentFunction();
}
});
答案 3 :(得分:-1)
<select class="recentOrPopular" name="mostpopular" id="dropdownPName" >
pName = document.getElementById('dropdownPName');
var value = pName.options[pName.selectedIndex].value;
switch(value)
{
case 'recent' : //call your function
case 'popular' : // call your function
}