jQuery(#id).val()与getElementById(#id).value [英] jQuery(#id).val() vs. getElementById(#id).value
问题描述
我一直在寻找,但我只能找到谈论其中一个的文章。哪一个更好?
I been searching but I can only find articles talking about one or the other. Which one is better?
我正在制作一个小型网络应用程序,性能不是一个大问题,因为没有什么复杂的事情发生。
I'm making a small web app where performance is not a big concern since there's nothing complex going on.
我考虑使用jQuery的 val()
函数,因为它可能解决了一些我不知道的不一致,但 getElementById。值
更快(尽管最终用户不会注意到。)
I considered using jQuery's val()
function since maybe it solves some inconsistency I'm not aware of, but getElementById.value
IS faster (although the end user won't notice.)
那么我应该使用哪一个? jQuery的非本机方法是否值得获得更高的兼容性?
So which one should I use? Is jQuery's non-native method worth the lower performance to gain more compatibility?
推荐答案
使用 jQuery()的最大优势.val()
over document.getElementById()。value
如果没有匹配的元素,前者将不抛出错误,后者将在哪里。 document.getElementById()
返回 null
如果没有匹配的元素,where-as jQuery( )
返回一个空的jQuery对象,它仍支持所有方法(但 val()
将返回undefined)。
The biggest advantage of using jQuery().val()
over document.getElementById().value
is that the former will not throw an error if no elements are matched, where-as the latter will. document.getElementById()
returns null
if no elements are matched, where-as jQuery()
returns an empty jQuery object, which still supports all methods (but val()
will return undefined).
对表单元素使用 .value
时,无不一致。但是,jQuery.val()标准化了用于在选择框中收集选定值的接口;在标准HTML中你必须使用 .options [this.selectedIndex] .value
。
There is no inconsistency when using .value
for form elements. However, jQuery.val() standardises the interface for collecting the selected value in select boxes; where as in standard HTML you have to resort to using .options[this.selectedIndex].value
.
这篇关于jQuery(#id).val()与getElementById(#id).value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!