jquery不知道选择了什么选项

时间:2013-02-24 23:42:02

标签: jquery html

HTML:

<p>
    <label for="rolle">Rolle:</label> 
    <select id="rolle" style="float:right;width:154px;" name="rolle">
        <option value="1">Administrator</option>
        <option value="2">Autor</option>
    </select> 
</p>

jQuery的:

$(document).ready(function()
{
    $('#rolle').change(function()
    {
        if($('#rolle option[value="1"]:selected')) 
        {
            alert("YES");
        }
    });
});

2 个答案:

答案 0 :(得分:2)

jQuery个函数返回jQuery个对象。如果您想知道是否有任何元素与查询匹配,则必须检查length属性。

将JavaScript更改为:

$(document).ready(function(){
    $('#rolle').change(function(){
        if($('#rolle option[value="1"]:selected').length > 0) {
            alert("YES");
        }
    });
});

答案 1 :(得分:1)

为什么不简单地转一下你的条件检查来阅读:

$(document).ready(function(){
    $('#rolle').change(function(){
        if($('#rolle option:selected').val() == "1") {
            alert("YES");
        }
    });
});
相关问题