为什么val()在列表上工作但属性不起作用?(Why val() work on a list but an attribute does not?)

编程入门 行业动态 更新时间:2024-10-10 09:23:49
为什么val()在列表上工作但属性不起作用?(Why val() work on a list but an attribute does not?)

这是我的咖啡

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')

更多推荐

本文发布于:2023-08-02 07:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1372707.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表上   不起作用   属性   工作   val

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!