如何从$(selector).each()访问prop

时间:2017-03-16 09:31:05

标签: jquery iteration

这是HTML片段

<select multiple>
    <option value="1">Option 1</option>
    <option value="2" selected>Option 2</option>
    <option value="3" selected>Option 3</option>
</select>

这是脚本

$('select option').each(function(index, elem) {
    if (elem.prop('selected')) {
        // Find a checkbox somewhere in the page that correspond with the option
        // and then check it.
    }
});

但这会引发elem.prop is not a function

即使是简单的console.log(elem.prop('selected'))也无效。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

您的问题是因为elem引用了一个Element,而不是一个jQuery对象。要做你需要的事,你需要像这样包裹elem

&#13;
&#13;
$('select option').each(function(index, elem) {
  var $elem = $(elem);
  if ($elem.prop('selected')) {
    console.log($elem.val());
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
    <option value="1">Option 1</option>
    <option value="2" selected>Option 2</option>
    <option value="3" selected>Option 3</option>
</select>
&#13;
&#13;
&#13;

但是你应该注意你的循环是多余的。您可以使用:selected选择器并完全避免循环:

&#13;
&#13;
var $elem = $('select option:selected');
console.log($elem.val());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
    <option value="1">Option 1</option>
    <option value="2" selected>Option 2</option>
    <option value="3" selected>Option 3</option>
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

$('select option').each(function(index, elem) {
  if ($(elem).prop('selected')) {
    // Find a checkbox somewhere in the page that correspond with the option
    // and then check it.
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
    <option value="1">Option 1</option>
    <option value="2" selected>Option 2</option>
    <option value="3" selected>Option 3</option>
</select>

你应该将elem放在$()