哪种方法可以更好地检查元素? .is(':checked')或.prop('checked') [英] Which way to test if an element is checked is better? .is(':checked') or .prop('checked')
问题描述
.is(':checked')
和.prop('checked')
均可用于测试是否选中了一个复选框.
Both .is(':checked')
and .prop('checked')
can be used to test if a checkbox is checked.
这两种查询 checked 状态的方法之间是否存在有趣/重要的区别?或者仅仅是个人喜好问题?
Are there any interesting/important differences between those two ways of querying the checked state or is it pretty much only a matter of personal preference?
推荐答案
他们最终都检查了同一件事.
They both end up checking the same thing.
如果您使用的是1.6.0或更高版本,则prop('checked')
是最直接的jQuery方式. jQuery不必解析和处理选择器即可确定要做什么. [下面的注意事项]
If you're using 1.6.0 or higher, prop('checked')
is the most direct jQuery way. jQuery doesn't have to parse and process a selector to figure out what to do.[Note below]
您也可以(从1.6.1版本开始)与1.5.x及更早版本一起使用attr('checked')
.
You can also (as of 1.6.1) use attr('checked')
again as with 1.5.x and earlier.
或者您可以直接转到元素.假设x
是要测试的东西,如果知道至少有一个元素匹配,则:
Or you can go directly to the element. Assuming x
is the thing to be tested, if you know that at least one element matched, then:
if (x[0].checked) { /* ... */ }
如果您不确定并希望对冲您的赌注:
If you're not sure and want to hedge your bets:
if (x[0] && x[0].checked) { /* ... */ }
但是,除非您陷入真正的困境,否则请使用您认为最容易阅读的内容,因为性能差异无关紧要.我发现最后一个非常容易阅读,而且我知道它们非常快,因此我使用它们.但是,如果您觉得它们很尴尬,请使用最喜欢的方法.如果您喜欢is(':checked')
并且没有看到实际的性能下降,也不会造成任何伤害(这不太可能再次出现某种紧密循环).
But unless you're in a really tight loop, use whatever you find easiest to read, as the performance differences aren't going to matter. I find the last ones quite easy to read and I know they're very fast, so I use them. But if you find them awkward, use whatever you like best. No harm in using is(':checked')
if you like it and you're not seeing an actual performance hit from it (which is unlikely barring, again, some kind of tight loop).
注意:prop
比is
更直接的学位因浏览器而异. prop
不仅是对属性的直接检查,而且确实会先经过几个间接层.和is
并不一定非常复杂:例如,在WebKit浏览器中,is
可以相当直接,因为WebKit提供了一个测试元素是否与选择器匹配的功能,并且本机支持:checked
.在Firefox(我怀疑是IE)上,is
导致大量的 函数调用,因为这个看似简单的选择器在Sizzle的内部发挥了作用.
Note: The degree to which prop
is more direct than is
varies by browser. prop
isn't just a direct check of a property, it does go through a couple of levels of indirection first; and is
isn't necessarily hugely complex: On WebKit browsers, for instance, is
can be fairly direct as WebKit provides a function to test whether an element matches a selector, and supports :checked
natively; on Firefox (and, I suspect, IE), is
results in a huge number of function calls as this seemingly-simple selector works its way through the guts of Sizzle.
这篇关于哪种方法可以更好地检查元素? .is(':checked')或.prop('checked')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!