2013-10-18 41 views
1

我有一个选择框,其中包含两个最近很流行的选项,要求是,如果我选择近期,则后端应调用以获得相应的回应,同样也应该为流行而发生。我经历了很多问题,但找不到我正在寻找的确切答案。我当前的代码看起来像这样每次从选择框中选择不同的选项时,想要调用不同的Javascript方法

<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

回答

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; 
    } 
}); 
+0

谢谢阿伦,这个工作我想这只是一个很多事情,我会读了jQuery明确的API下一次。非常感谢。 – kavinder

-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 

} 
+0

不是jQuery的粉丝我看到...除非有特定的原因 - 没有必要混合原生JS和jQuery这样... – Lix

+0

@Lix有什么不对吗? – Shadow

+0

是的 - jQuery用于防止使用'getElementById'和其他原生JS函数。你为什么选择不在这里使用jQuery? – Lix

2
$('.recentOrPopular').val('popular') 

是使用SET值,如果你想比较他们使用

if($('.recentOrPopular').val() == 'popular') 

另外,代替if()和if()使用if ... else if()这可以确保如果第一个条件满足,第二个条件不会执行。

+1

甚至更​​好 - 一个开关盒,以便OP可以根据需要添加越来越多的选项。添加几个项目后,if-else构造将变得难以管理。 – Lix

0

修改代码为

$(".recentOrPopular").change(function() { 
    if($('.recentOrPopular').val()=='popular'){ 
     this.myPopularFunction(); 
    } 
    if($('.recentOrPopular').val()=='recent'){ 
     this.myrecentFunction(); 
    } 
}); 
相关问题