jQuery .val()与.attr(“值”) [英] jQuery .val() vs .attr("value")
问题描述
$ obj.attr(value)
来处理表单字段,但是在我正在构建的页面上, $ obj.attr(value)
不会返回我在我的字段中输入的文本。但是, $ obj.val()
没有。 在我创建的不同页面上, $ obj.attr(value)
和 $ obj.val()
返回在表单域中输入的文本。
可以解释 $ obj.attr(value)
在一种情况下按预期工作,但不在另一个?
使用jQuery设置和检索表单字段值的正确方法是什么?
对象属性与对象属性之间存在大差异
查看以下问题(及其答案)的一些差异: .prop()vs .attr()
要点在于 .attr(...)
只能获取对象值at开始(当html被创建时)。 val()
正在获取对象的属性值,该值可以更改很多次。
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.
On a different page I've built, both $obj.attr("value")
and $obj.val()
return the text entered in the form field.
What could account for $obj.attr("value")
working as expected in one case but not in another?
What is the proper way to set and retrieve a form field's value using jQuery?
There is a big difference between an objects properties and an objects attributes
See this questions (and its answers) for some of the differences: .prop() vs .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 property value which can change many times.
这篇关于jQuery .val()与.attr(“值”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!