2012-02-06 189 views
4

如何在选择默认值时允许我的更改事件发生在我的下拉菜单中?JQuery选择下拉更改事件 - 选择默认值

选择值1为默认值,但也有变化功能的工作..

<select id='statsGraphingSelect'> 
    <option value='1' selected="selected">1</option> 
    <option value='2'>2</option> 
    <option value='3'>3</option> 
    <option value='4'>4</option> 
</select>  

$("#statsGraphingSelect").change(function() { 
    if ($("#statsGraphingSelect option[value='1']").attr('selected')) {//something happens here } 
    if ($("#statsGraphingSelect option[value='2']").attr('selected')) {//something happens here } 
    if ($("#statsGraphingSelect option[value='3']").attr('selected')) {//something happens here } 
    if ($("#statsGraphingSelect option[value='4']").attr('selected')) {//something happens here } 
} 

回答

16

我不知道什么是你想实现的,你可以尝试

$("#statsGraphingSelect").change(function() { 
var n = $(this).val(); 
switch(n) 
{ 
case '1': 
    execute code block 1 
    break; 
case '2': 
    execute code block 2 
    break; 

} 
}); 
现在你给

标记,如果你喜欢触发

$(function(){ 
$("#statsGraphingSelect").change(); 
}); 

case 1无线就绪处理程序变化将被执行

DEMO

+0

这很有效,谢谢。在用户引起变化事件之前,最初设置跑步说case 1的情况如何? – user1040259 2012-02-06 23:21:56

+0

@ user1040259查看答案更新 – Rafay 2012-02-06 23:22:25

+0

@ user1040259再次用演示更新了答案,看一看 – Rafay 2012-02-06 23:37:09