.prop()VS .val()。使用jQuery设置输入文本值 [英] .prop() VS .val() .Setting an input text value with jQuery
问题描述
阅读(有趣的),同时.prop()更快
EDIT3:
正如@BeatAlex所说,如果我们希望性能原生js 显示 val()
比更快> prop()
。
由于你喜欢显示一些图形和图片,我将添加一些:
取自此链接
如果你争论超速,纯JS会更好。
After reading (the interesting) .prop() vs .attr() and jQuery Performance : attributes doubt arise in my mind about what is better to use: .prop() or .val() ? I want to set an input text value.
The jQuery .prop() page said the following:
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.
But regarding to performance .prop() seems to be better than .val() setting values:
So I don't have an answer. What I should do?
$('#element').prop('value', 'Example');
or
$('#element').val('Example');
EDIT1: .prop() is always better than .val()
EDIT2: I've tried now getting a value, also .prop() is faster
EDIT3: As @BeatAlex says if we want performace native js is extremely faster
var x = document.getElementById('element').value;
As some of you said it may be faster, but if .val() exist we'd use it.
PS: while I am writing this, current jQuery version is 1.11 or 2.1
You want to use val()
. That's what the function is for, specifically for the val
ue of the input.
It's also quicker to write, easier to understand and while using val
, you can change the value multiple times if need be.
Your chart says
Higher is better
and val()
higher.
Also, like you've already quoted,
The .val() method should be used for getting and setting value.
This means that unless you're dealing with disabled properties, use:
$('input').val();
Also as a side note, the link you posted, after running tests, shows that val()
is faster than prop()
.
Since you LOVE to show some graphs and pictures, i'm going to add some:
Taken from this link
Pure JS is better if you're arguing over speed.
这篇关于.prop()VS .val()。使用jQuery设置输入文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!