问题描述
我试图在jQuery中设置一个变量。该值应该设置在按钮的单击事件上。 onclick事件触发,但x10Device变量仍然是 undefined
。
我在jquery 1.7.1上。
jQuery:
$ x10Device = $(this).data(X10);
HTML:
< button class =toggleStatusdata-X10 =C5>
我看不到有什么不对。
data - *
属性,但是,它破坏了属性名称的情况。你可以使用这个: $('#myButton')。data(x10)//注意小写
或者,您可以使用 attr()
方法,它保留你的情况:
$('#myButton')。attr(data-X10)
试试这两种方法:
请注意,这些方法并不完全等效。如果您要更改元素的 data - *
属性,则应该使用 attr()
。 data()
会在最初读取一次值,然后继续返回一个缓存副本,而 attr()
- 每次读取属性。
请注意,jQuery还会将属性名称中的连字符转换为骆驼大小写( - 即 data-some-data == $(ele).data( 'someData')
)。这两种转换都符合HTML规范,该规范规定自定义数据属性不应包含大写字母,并且连字符将在数据集
属性中驼峰化)。 jQuery的 data
方法仅仅模仿/符合这种标准行为。 $ b
文档
-
data
- -
attr
- - HTML语义和结构,自定义数据属性 -
I am trying to set a variable in jQuery. The value is supposed to be set on the click event of the button. The onclick event fires but the x10Device variable remains undefined
.
I am on jquery 1.7.1.
jQuery:
$x10Device = $(this).data("X10");
HTML:
<button class="toggleStatus" data-X10="C5">
I can't see what's wrong.
jQuery's data()
method will give you access to data-*
attributes, BUT, it clobbers the case of the attribute name. You can either use this:
$('#myButton').data("x10") // note the lower case
Or, you can use the attr()
method, which preserves your case:
$('#myButton').attr("data-X10")
Try both methods here: http://jsfiddle.net/q5rbL/
Be aware that these approaches are not completely equivalent. If you will change the data-*
attribute of an element, you should use attr()
. data()
will read the value once initially, then continue to return a cached copy, whereas attr()
will re-read the attribute each time.
Note that jQuery will also convert hyphens in the attribute name to camel case (source -- i.e. data-some-data == $(ele).data('someData')
). Both of these conversions are in conformance with the HTML specification, which dictates that custom data attributes should contain no uppercase letters, and that hyphens will be camel-cased in the dataset
property (source). jQuery's data
method is merely mimicking/conforming to this standard behavior.
Documentation
data
- http://api.jquery.com/data/attr
- http://api.jquery.com/attr/- HTML Semantics and Structure, custom data attributes - http://www.w3.org/html/wg/drafts/html/master/dom.html#custom-data-attribute
这篇关于jquery无法获取数据属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!