2017-04-25 82 views
0

我在我的选择选项脚本中有一些问题,但我不明白,什么是错的?对不起,我不是真正的jQuery专家。做一些选择开关

HTML

<fieldset> 
<select id="sorting"> 
    <option value="1">A-Z</option> 
    <option value="2">Number</option> 
</select> 
</fieldset> 

jQuery的

$(document).change(function() { 
    if($("#sorting").prop("selectedIndex", 1)) { 
     alert("A-Z"); 
    } 
    else if($("#sorting").prop("selectedIndex", 2)) { 
     alert("Number"); 
    }   
}); 

我的问题:它总是 “AZ”,我不能切换到 “数字” 选择号码;(

这里是我的fiddle

+0

非常简单 - > https://jsfiddle.net/bymfjrfk/1/ – adeneo

回答

4

使用.val()获取选择的值:

$("#sorting").change(function() { 
 
    if ($(this).val() == 1) { 
 
    alert("A-Z"); 
 
    } else if ($(this).val() == 2) { 
 
    alert("Number"); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<fieldset> 
 
    <select id="sorting"> 
 
    <option value="1">A-Z</option> 
 
    <option value="2">Number</option> 
 
    </select> 
 
</fieldset>

+1

啊,好的,非常感谢!很棒。 – Pepe

2

要设置没有得到所选择的指数,但指数也是零基础

更改为:

$(document).on('change','#sorting', function() { 
    var selectedIndex = this.selectedIndex; 
    if(selectedIndex === 0) { 
     alert("A-Z"); 
    } 
    else if(selectedIndex === 1) { 
     alert("Number"); 
    }   
}); 
+0

哎,该死的,这很有道理!谢谢! – Pepe

+0

我选择j08691解决方案,因为它有点更聪明,但我投票支持你的版本,因为你可以帮我找到脚本版本的失败 - 所以也要谢谢! – Pepe

0

你在设定 HTML属性,因此在jQuery中使用.val()以获取期权的价值。