区别:checked和:在jQuery中使用选项元素时选择 [英] Difference between :checked and :selected when working with option elements in jQuery
问题描述
:选中
和:选中
似乎在使用<时提供相同的结果;选项>
元素。使用一个优于另一个是否有任何优势?如果:selected
与:check
做同样的事情,那么将它包含在jQuery中的原因是什么?
Both :checked
and :selected
seem to provide equal results when working with <option>
elements. Is there any advantage to using one over the other? If :selected
does the same thing as :checked
, what is the reason for it to be included in jQuery at all?
示例:
<p class="p1">Select a value</p>
<p class="p2">Select a value</p>
<select>
<option value="a">Option one</option>
<option value="b">Option two</option>
</select>
$('select').on('change', function(){
$('.p1').text(function() {
return $('option:selected').text();
});
$('.p2').text(function() {
return $('option:checked').text();
});
});
推荐答案
判断文档,似乎:selected
与:已检查
,但它仅匹配选项
元素。这是由HTMLOptionElement证实的,它是DOM中唯一具有选择的
属性的元素类型(这是:selected
用于测试元素的选择性)。换句话说,当您只对选项
元素感兴趣时,两个选择器都是相同的 - 除了:selected
是非-standard。
Judging by the documentation, it seems that :selected
is identical to :checked
with the exception that it only matches option
elements. This is corroborated by HTMLOptionElement being the only element type in the DOM to have a selected
property (which is what :selected
uses to test the selectedness of an element). In other words, when you're only interested in option
elements, both selectors are identical — except :selected
is non-standard.
由于文档本身建议使用标准选择器来最大化性能(并且因为为什么不使用标准选择器而不是非 - 如果有选择的标准吗?),我认为没有任何理由在任何情况下都使用:selected
。我想不出任何情况 *:选择
比选项更好:选中
(严重的是,当是你最后一次使用这种没有类型选择器的伪类吗?)。
Since the documentation itself recommends using standard selectors to maximize performance (and because why would you not use a standard selector over a non-standard one if given the choice?), I don't think there is any reason to use :selected
in any situation ever. I can't think of any situation in which *:selected
would be preferable to option:checked
(seriously, when was the last time you used a pseudo-class of this kind without a type selector?).
也许它被包含在jQuery中的原因是因为选择器3(其中) :已检查
出现)jQuery诞生时尚未标准化,但:已检查
已在规范中自2000年以来,所以我并不完全相信这是真的原因。
Perhaps the reason it was included in jQuery was because Selectors 3 (in which :checked
appears) wasn't yet standardized at the time jQuery was born, but :checked
has been in the spec since 2000, so I'm not entirely convinced that's really the reason.
这篇关于区别:checked和:在jQuery中使用选项元素时选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!