这是我的咖啡
name = @$ '#require-name' console.log name.val()显然, name是一个元素列表。 但是, val()可以正确返回列表中唯一元素所持有的值。
但是如果我想获得这个元素的属性的值,我会得到undefined 。 为什么是这样?
在代码的其他部分,我想单独引用这个元素#require-name 。 所以我写这个
name = @$('#require-name')[0]它对我来说并不是很优雅。 我想取消索引( [0] ),因为只有这一个元素。 有没有更好的方式表达这个?
This is my coffeescript
name = @$ '#require-name' console.log name.val()Apparently name is a list of element. However the val() can correctly return the value held by the only element in the list.
But if I want to get the value of an attribute of this element, I get undefined. Why is this?
In other part of the code I want to refer to this element #require-name alone. So I write this as
name = @$('#require-name')[0]It does not feel very elegant to me. I want to do away the indexing ([0]) since there will only be this one element. Is there a better way to express this?
最满意答案
$('#require-name')返回jQuery对象,因此.val()用于获取值。 @$('#require-name')[0]返回基础DOM元素,因此您可以访问name.checked等name.checked
或者,您可以使用.prop()方法
$('#require-name').prop('checked')$('#require-name') returns you jQuery object thus .val() is used for fetching the values. Where as @$('#require-name')[0] return you underlying DOM element thus you can access properties like name.checked
Or, You can use .prop() method
$('#require-name').prop('checked')更多推荐
发布评论