jquery :selected not working right?

标签 jquery jquery-selectors

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

http://jsfiddle.net/fdU83/6/

关于jquery :selected not working right?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9677632/

相关文章:

javascript - 如何获取元素的类型。 JavaScript/jQuery

jQuery 选择后代,包括父级

javascript - 使用 JQuery UI 的内联幻灯片效果

javascript - 显示数组的前 4 个,然后显示后 4 个

jQuery 验证输入是否不为空

jquery - 单击元素外部任意位置时隐藏元素

jquery - 在表中查找 <tr>

javascript - 使用 javascript 隐藏数字,而不使用 jQuery

jquery - 如何使用jquery从类的第二个元素中获取值?

html - 当 <body> 是父级时,为什么 ":last-child"选择器不适用?