为什么jQuery .data()函数没有访问HTML5 camel-case数据属性 [英] Why jQuery .data() function is not accessing HTML5 camel-case data attribute
问题描述
我的网页上有一个按钮:
I have a button in my web page:
<button class="slideToggle" data-slideToggle="slider">SlideToggle</button>
单击此按钮时,我试图访问存储在data-slideToggle属性中的数据通过使用以下代码,但我什么都没得到。
When this button is clicked I am trying to access the data that is stored inside the data-slideToggle attribute by useing the following code, but I get nothing.
$('body').on('click', '.slideToggle', function(){
alert($(this).data('slideToggle'));
});
但是当我使用时它可以工作:
but it works when I use:
alert($(this).attr('data-slideToggle'));
当我使用camel-case数据属性时会出现此问题。我是HTML5和jQuery的新手,我无法弄清楚它出了什么问题。
This problem occurs when I use camel-case data attribute. I am very new to HTML5 and jQuery and I can not figure out what is going wrong with it.
推荐答案
所有以前的答案想念一件事:你实际上可以使用现有的HTML结构。考虑一下:
All the previous answers miss one thing: you actually can work with existing HTML structure. Consider this:
$('body').on('click', '.slideToggle', function(){
alert($(this).data('slidetoggle')); // wait, what?
});
要了解这里发生的事情,检查 jQuery源代码:
To understand what happens here, it's crucial to check the following lines in jQuery source code:
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
请参阅,jQuery遵循数据集API的约定,转换 fooBar
property into data-foo-bar
元素属性的名称。
See, jQuery here follows the convention of Dataset API, converting the fooBar
property into data-foo-bar
name of the element's attribute.
在您的情况下,将'slideToggle'
转换为'data-slide-toggle '
- 显然你的HTML中没有这样的属性。
In your case, that converts 'slideToggle'
to 'data-slide-toggle'
- and there's no such attribute in your HTML, apparently.
然而,数据('slidetoggle')
工作正常,因为 getAttribute
默认情况下会在Element的属性中执行不区分大小写的搜索。因此,您甚至可以将其写为......
However, data('slidetoggle')
works fine, as getAttribute
by default performs a case-insensitive search among Element's attributes. Therefore, you might even wrote that one as...
<button data-sLiDeToGgLe="l33t!"></button>
......它仍然是 会起作用 。 )
... and it still would have worked. )
不过,我宁愿建议遵循数据集API约定,将camelCased complexWord
数据属性分解为连字符 complex-word
表示法。
Still, I'd rather recommend following the Dataset API convention, breaking camelCased complexWord
data attributes into hyphenated complex-word
notation.
这篇关于为什么jQuery .data()函数没有访问HTML5 camel-case数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!