jQuery .val() 与 .attr("value") [英] jQuery .val() vs .attr("value")

查看:27
本文介绍了jQuery .val() 与 .attr("value")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我原以为这两个是一样的,但他们似乎不是.我通常使用 $obj.attr("value") 来处理表单字段,但在我目前正在构建的页面上, $obj.attr("value") 不会返回我在字段中输入的文本.但是, $obj.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.

在我构建的另一个页面上,$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") 在一种情况下按预期工作但在另一种情况下不能正常工作?

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

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

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

请参阅此问题(及其答案)以了解一些差异:.prop() 与 .attr()

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

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

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("value")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆