javascript - .attr ("value") 总是返回未定义?

标签 javascript jquery html

我有一个隐藏元素,在我的 jQuery 中:

<input type="hidden" id="1val" value="24">
var valID = $("#1val").attr("value");

但是,当我尝试打印 valID 时,它总是打印为未定义?我做错了什么?

谢谢

最佳答案

使用 .prop().val() 方法获取当前 value 属性总是更安全:

var valID = $("#1val").val();
// or
var valID = $("#1val").prop("value");

从 jQuery 版本 1.9 开始,.attr() 方法只会获取元素的属性,这实际上可能无法反射(reflect)元素的实际属性。


根据版本1.9 release notes ,在 .attr().prop() 下:

The value property versus attribute on input elements is another example of this ambiguity. The attribute generally reflects the value that was read from the HTML markup; the property reflects the current value. Since the .val() method is the recommended jQuery way to get or set the values of form elements, this confusion usually does not affect users.

However, when a selector like input[value=abc] is used, it should always select by the value attribute and not any change made to the property by the user, for example from them typing into a text input. As of jQuery 1.9, this behaves correctly and consistently. Earlier versions of jQuery would sometimes use the property when they should have used the attribute.

在幕后,从 1.9 版开始,.attr() 方法将只返回元素的当前属性(而不是属性)。属性和属性实际上可能并不相同。例如,如果元素上最初没有属性,然后使用 .val() 等方法以编程方式设置值,则属性不会改变,这意味着 .attr('value') 将返回 undefined

如上所述,使用.prop().val() 方法来获取元素的当前value 属性。

关于javascript - .attr ("value") 总是返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35107760/

相关文章:

javascript - 当用户按下 "Ctrl+V"时如何在 Firefox 中获取剪贴板文本和 html

javascript - 如果时间戳在 aws 上使用 golang 生成,则在本地系统上显示不同的日期时间

jquery - 在没有命名空间的jquery中触发事件

javascript - jquery stopPropagation() 并发送 "event"?

javascript - 点击下拉菜单

javascript - 当使用服务和 API 登录以在 MySQL 中获取时,Angularjs 在 $scope 中显示特定用户的动态 ID 和信息

javascript - 使用 JavaScript 从二进制文件中读取字节,无需 jQuery

javascript - 我应该监听哪些事件以在 JavaScript 中隐藏自定义上下文菜单

javascript - 在视口(viewport)内显示一个 div

html - Overflow-y 无法在 body 上的 div 上正常工作