jQuery .val() 和 .attr('value') 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4837133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:00:51  来源:igfitidea点击:

What's the difference between jQuery .val() and .attr('value')?

jquery

提问by The Coding Monk

I think the title is clear enough

我觉得标题已经够清楚了

回答by Nick Craver

.val()works on all input type elements in a useful way, including <select>...even in the cases of <select multiple>, checkboxes, and radio buttons (in which .val()gets or sets an arrayof selected values not just a string).

.val()以一种有用的方式处理所有输入类型元素,包括<select>...甚至在<select multiple>、复选框和单选按钮(其中.val()获取或设置一选定值而不仅仅是字符串)的情况下。

So basically they serve different purposes, even though .attr('value')behaves the same in some situations, like textboxes. The preferred method is .val()to get consistent behavior everywhere.

所以基本上它们服务于不同的目的,即使.attr('value')在某些情况下表现相同,比如文本框。首选方法是.val()在任何地方获得一致的行为。



Just for kicks, here's a lesser-known example for checkboxes that makes .val()handy:

只是为了踢球,这是一个鲜为人知的复选框示例,它.val()很方便:

<input name="mytest" type="checkbox" value="1">
<input name="mytest" type="checkbox" value="2">
<input name="mytest" type="checkbox" value="3">
<input name="mytest" type="checkbox" value="4">

You can do this:

你可以这样做:

$("input[name='mytest']").val([1, 2, 3]);

....which will check the first 3 boxes. You can give it a try here.

....这将检查前 3 个框。 你可以在这里试一试

回答by actis

Also .attr('value') returns the value that was before editing input field. And .val() returns the current value.

此外 .attr('value') 返回编辑输入字段之前的值。.val() 返回当前值。

回答by user3624334

To add to actis's answer...

添加到actis的答案...

Also .attr('value') returns the value that was before editing input field. And .val() returns the current value.

此外 .attr('value') 返回编辑输入字段之前的值。.val() 返回当前值。

When working with a text entry field, the setter methods of .attr() and .val() work differently.

使用文本输入字段时,.attr() 和 .val() 的 setter 方法的工作方式不同。

.val('newval')

will set the value the user sees on the page and update the value returned by subsequent .val() method calls. It will not set the value= attribute of the element.

将设置用户在页面上看到的值并更新后续 .val() 方法调用返回的值。它不会设置元素的 value= 属性。

OTOH

奥托

.attr('value','newval')

will set the value= attribute on the element. If the user hasn't typed and .val(newval) hasn't been called, then doing this will also visually update the control and update the value returned by .val().

将在元素上设置 value= 属性。如果用户没有输入并且 .val(newval) 没有被调用,那么这样做也会在视觉上更新控件并更新 .val() 返回的值。

You can investigate further with the following jsfiddle:

您可以使用以下 jsfiddle 进一步调查:

https://jsfiddle.net/jasonnet/vamLww2k/

https://jsfiddle.net/jasonnet/vamLww2k/

Good luck.

祝你好运。