读完后(有趣的).prop() 与 .attr() and jQuery 性能:属性我心中出现了关于哪个更好使用的疑问: .prop() 还是 .val() ?我想设置一个输入文本值。
The jQuery .prop() 页面说道:
属性通常会影响 DOM 元素的动态状态,而不更改序列化的 HTML 属性。示例包括输入元素的值属性、输入和按钮的禁用属性或复选框的选中属性。应该使用 .prop() 方法来设置禁用和检查,而不是 .attr() 方法。.val() 方法应用于获取和设置值.
But regarding to performance .prop() seems to be better than .val() setting values:
![.prop() vs .attr() vs .val()](https://i.stack.imgur.com/lVnjZ.png)
所以我没有答案。
我该做什么?
$('#element').prop('value', 'Example');
or
$('#element').val('Example');
EDIT1:
.prop() is always better than .val()
![enter image description here](https://i.stack.imgur.com/1q7x4.png)
EDIT2:
I've tried now getting a value, also .prop() is faster
![enter image description here](https://i.stack.imgur.com/m8U0y.png)
EDIT3:正如 @BeatAlex 所说,如果我们想要性能原生 js 就是速度极快
var x = document.getElementById('element').value;
![enter image description here](https://i.stack.imgur.com/NhgQx.png)
正如你们中的一些人所说,它可能会更快,但如果 .val() 存在,我们会使用它。
PS:当我写这篇文章时,当前的 jQuery 版本是 1.11 或 2.1