jquery不知道选择了什么选项



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");
        }
    });
});

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

将JavaScript更改为:

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

为什么不简单地将条件检查稍微转一转,阅读以下内容:

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

相关内容

最新更新