我有一个隐藏元素,在我的 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/