documentation对于 jQuery 的 :selected
选择器来说,使用它的正确方法是使用,例如 $('select').filter(':selected')
。但是,我无法让它工作!它仅在我使用诸如 $('select :selected')
之类的东西时才有效。
这是一个最小的示例,以及 my jsFiddle implementation of it :
JavaScript:
function getLengths() {
$("#dothis").text($("select").filter(":selected").length);
$("#dothat").text($("select :selected").length);
}
$(function() {
getLengths();
$("select").change(getLengths);
});
相关html:
<select multiple="multiple">
<option selected="true">one</option>
<option>two</option>
</select>
<div>
<pre>$("select").filter(":selected").length = <span id="dothis"></span></pre>
<pre>$("select :selected").length = <span id="dothat"></span></pre>
</div>
最佳答案
过滤选项元素,而不是选择:
function getLengths() {
$("#dothis").text($("option").filter(":selected").length);
$("#dothat").text($("select :selected").length);
}
$(function() {
getLengths();
$("select").change(getLengths);
});
关于jquery :selected not working right?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9677632/