jQuery .val() 与 .attr("value")

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8312820/
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-27 10:20:07  来源:igfitidea点击:

jQuery .val() vs .attr("value")

jqueryforms

提问by morgancodes

I had thought these two were the same, but they appear to not be. I've generally been using $obj.attr("value")to work with form fields, but on the page I'm currently building, $obj.attr("value")does not return the text I enter in my field. However, $obj.val()does.

我原以为这两个是一样的,但他们似乎不是。我通常一直在使用$obj.attr("value")表单字段,但在我当前正在构建的页面上,$obj.attr("value")不会返回我在字段中输入的文本。然而,$obj.val()确实如此。

On a different page I've built, both $obj.attr("value")and $obj.val()return the text entered in the form field.

在不同的页面我已经建立,双方$obj.attr("value")$obj.val()返回在表单字段中输入的文本。

What could account for $obj.attr("value")working as expected in one case but not in another?

什么可以解释$obj.attr("value")在一种情况下按预期工作但在另一种情况下不能正常工作?

What is the proper way to set and retrieve a form field's value using jQuery?

使用 jQuery 设置和检索表单字段值的正确方法是什么?

回答by Naftali aka Neal

There is a bigdifference between an objects propertiesand an objects attributes

对象属性和对象属性之间存在很大差异

See this questions (and its answers) for some of the differences: .prop() vs .attr()

有关一些差异,请参阅此问题(及其答案):.prop() 与 .attr()

The gist is that .attr(...)is only getting the objects value at the start (when the html is created). val()is getting the object's propertyvalue which can change many times.

要点是.attr(...)仅在开始时(创建 html 时)获取对象值。val()正在获取可以多次更改的对象的属性值。

回答by Frédéric Hamidi

Since jQuery 1.6, attr()will return the original value of an attribute (the one in the markup itself). You need to use prop()to get the current value:

从 jQuery 1.6 开始,attr()将返回属性的原始值(标记本身中的值)。您需要使用prop()来获取当前值:

var currentValue = $obj.prop("value");

However, using val()is not always the same. For instance, the value of <select>elements is actually the value of their selected option. val()takes that into account, but prop()does not. For this reason, val()is preferred.

但是,使用val()并不总是相同的。例如,<select>元素的值实际上是它们选择的选项的值。val()考虑到这一点,但prop()没有。为此,val()是首选。

回答by ρss

PS:This is not an answer but just a supplement to the above answers.

PS:这不是答案,只是对上述答案的补充。

Just for the future reference, I have included a good example that might help us to clear our doubt:

仅供将来参考,我提供了一个很好的例子,可以帮助我们消除疑虑:

Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected: The HTML code is below:

请尝试以下操作。在这个例子中,我将创建一个可用于选择文件的文件选择器,然后我将尝试检索我选择的文件的名称: HTML 代码如下

<html>
    <body>
        <form action="#" method="post">
            <input id ="myfile" type="file"/>
        </form>
        <script type="text/javascript" src="jquery.js"> </script>
        <script type="text/javascript" src="code.js"> </script>
    </body>
</html>

The code.js file contains the following jQuery code. Try to use both of the jQuery code snippets one by one and see the output.

code.js 文件包含以下 jQuery 代码。尝试一一使用这两个 jQuery 代码片段并查看输出。

jQuery code with attr('value'):

带有 attr('value') 的 jQuery 代码:

$('#myfile').change(function(){
    alert($(this).attr('value'));
    $('#mybutton').removeAttr('disabled');
});

jQuery code with val():

带有 val() 的 jQuery 代码:

$('#myfile').change(function(){
    alert($(this).val());
    $('#mybutton').removeAttr('disabled');
});

Output:

输出:

The output of jQuery code with attr('value') will be 'undefined'. The output of jQuery code with val() will the file name that you selected.

带有 attr('value') 的 jQuery 代码的输出将是 'undefined'。带有 val() 的 jQuery 代码的输出将是您选择的文件名。

Explanation: Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.

说明:现在您可以很容易地理解最重要的答案想要传达的内容了。带有 attr('value') 的 jQuery 代码的输出将是“未定义”,因为最初没有选择文件,因此该值是未定义的。最好使用 val() 因为它获取当前值。

In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.

为了了解返回未定义值的原因,请在您的 HTML 中尝试此代码,您将看到现在 attr.('value') 总是返回 'test',因为该值是 'test' 而以前它是未定义的。

<input id ="myfile" type="file" value='test'/>

I hope it was useful to you.

我希望它对你有用。

回答by Emre Erkan

The proper way to set and get the value of a form field is using .val()method.

设置和获取表单字段值的正确方法是使用.val()方法。

$('#field').val('test'); // Set
var value = $('#field').val(); // Get

With jQuery 1.6 there is a new method called .prop().

在 jQuery 1.6 中,有一个名为.prop().

As of jQuery 1.6, the .attr()method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

从 jQuery 1.6 开始,该.attr()方法为尚未设置的属性返回 undefined。此外,.attr() 不应用于普通对象、数组、窗口或文档。要检索和更改 DOM 属性,请使用 .prop() 方法。

回答by ShankarSangoli

In order to get the valueof any input field, you should always use $element.val()because jQueryhandles to retrieve the correct value based on the browser of the element type.

为了获取value任何输入字段的 ,您应该始终使用$element.val()因为jQuery句柄来根据元素类型的浏览器检索正确的值。

回答by Saloni Kalra

Let's learn from an example. Let there be a text input field with default value = "Enter your name"

让我们从一个例子中学习。让有一个默认值=“输入你的名字”的文本输入字段

var inp = $("input").attr("value");

var inp = $("input").val();

Both will return "Enter your name"

两者都会返回“输入你的名字”

But suppose you change the default text to "Jose" in your browser.

但是假设您在浏览器中将默认文本更改为“Jose”。

var inp = $("input").attr("value");

will still give the default text i.e. "Enter your name".

仍将提供默认文本,即“输入您的姓名”。

var inp = $("input").val();

But .val()will return "Jose", i.e. the current value.

.val()会返回“Jose”,即当前值。

Hope it helps.

希望能帮助到你。

回答by Moseyza

this example may be useful:

这个例子可能有用:

<html>
  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
  </head>
  <body>
 <input id="test" type="text"  />
 <button onclick="testF()" >click</button>
 
 
 <script>
 function testF(){
 
  alert($('#test').attr('value'));
  alert( $('#test').prop('value'));
  alert($('#test').val());
  }
 </script>
  </body>
 </html>

in above example, everything works perfectly. but if you change the version of jquery to 1.9.1 or newer in script tag you will see "undefined" in the first alert. attr('value') doesn't work with jquery version 1.9.1 or newer.

在上面的例子中,一切正常。但是,如果您在脚本标记中将 jquery 的版本更改为 1.9.1 或更高版本,您将在第一个警报中看到“未定义”。attr('value') 不适用于 jquery 1.9.1 或更新版本。

回答by harsimer

jQuery('.changer').change(function () {
    var addressdata = jQuery('option:selected', this).attr('address');
    jQuery("#showadd").text(addressdata);
});

回答by harsimer

jQuery(".morepost").live("click", function() { 
var loadID = jQuery(this).attr('id'); //get the id 
alert(loadID);    
});

you can also get the value of id using .attr()

您还可以使用 .attr() 获取 id 的值

回答by KingRider

Example more... attr() is various, val() is just one! Prop is boolean are different.

示例更多... attr() 是多种多样的,val() 只是其中之一!道具是布尔值是不同的。

//EXAMPLE 1 - RESULT
$('div').append($('input.idone').attr('value')).append('<br>');
$('div').append($('input[name=nametwo]').attr('family')).append('<br>');
$('div').append($('input#idtwo').attr('name')).append('<br>');
$('div').append($('input[name=nameone]').attr('value'));

$('div').append('<hr>'); //EXAMPLE 2
$('div').append($('input.idone').val()).append('<br>');

$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VAL
$('div').append($('input.idone').val('idonenew')).append('<br>');
$('input.idone').attr('type','initial');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VALUE
$('div').append($('input[name=nametwo]').attr('value', 'new-jquery-pro')).append('<br>');
$('input#idtwo').attr('type','initial');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" class="idone" name="nameone" value="one-test" family="family-number-one">
<input type="hidden" id="idtwo" name="nametwo" value="two-test" family="family-number-two">
<br>
<div></div>