在jQuery中使用数据属性
我有这个按钮:在jQuery中使用数据属性,jquery,Jquery,我有这个按钮: <button type="button" class="themeChanger" data-themeValue="grid" value="Grid"> <img src="templateImages/Icon_200.png" /> </button> 出于某种原因,第一个警报显示“网格”,但第二个警报显示未定义。有什么愚蠢的东西我遗漏了吗?我想数据应该是小写的:alert($(this.dat
<button type="button" class="themeChanger" data-themeValue="grid" value="Grid">
<img src="templateImages/Icon_200.png" />
</button>
出于某种原因,第一个警报显示“网格”,但第二个警报显示未定义。有什么愚蠢的东西我遗漏了吗?我想数据应该是小写的:
alert($(this.data)(“themevalue”)//grid
或者,如果要使用评估值,则需要使用:
编辑:
我错了,它与小写没有任何关系,如果您具有以下属性,则可以使用themeValue:数据主题值
,然后使用$(element.data(“themeValue”)调用它
$(“.themechance”)。单击(函数(){
var el=$(本);
警报($(this.data(“themeValue”);//Theme2
警报($(this.data(“themevalue”);//Theme1
});
我认为数据标记实现中的连字号的驼峰式大小写才是关键所在
试试这个jsfiddle-
数据主题值
数据评估值
$(“.themechance”)。单击(函数(){
警报($(this.attr(“数据themeValue”));
警报($(this.data)(“themeValue”);
});
问题在于驼峰案例。为了清楚起见,我坚持使用属性的数据主题值
格式
jquery自动将.data('some-value')
转换为数据('someValue')
请注意,这两个警报调用都返回grid
,如中所述,HTML5data-*
属性由浏览器->JS转换处理,处理方式与CSS名称相同,即:
数据-
被删除(我在上面绘制的CSS名称比较中不需要这个步骤)
变成data specialInfo
specialInfo
变成data more specialInfo
more specialInfo
-
变成specialInfo
[specialInfo]
变成more specialInfo
[更多,specialInfo]
变成[specialInfo]
[specialInfo]
变为[more,specialInfo]
(没有变化,因为第一部分已经更低了)[more,specialInfo]
变为[specialinfo]
(没有更改,因为没有其他部分)[specialinfo]
变成[more,specialInfo]
[more,specialInfo]
变成[specialinfo]
specialinfo
变成[more,Specialinfo]
moresspecialInfo
数据themeValue
属性可以通过$(This.data(“themeValue”)
访问。而数据主题值
属性可以通过$(this.data(“themeValue”)
访问
除非你认识到正在使用的机制,否则这是非常令人困惑的。OP问题的问题在于连字符和驼峰式大小写多于小写。我真的不明白你的意思。“他们”是谁?无论如何,由于HTML和JavaScript之间的sytanx差异,上述过程是必要的(实际上并不是那么复杂)。谢谢您的回答。我觉得这很烦人-为什么jQuery强制我使用特定的符号?没问题,很高兴它有帮助。在许多现代浏览器中,data attr API以某种形式存在,没有jQuery。jQuery在它不存在的地方提供它,并在它存在的地方扩展它。在这种情况下,他们必须使其兼容。其实也没那么糟糕,只是要习惯一下。这与从JS设置CSS值没有什么不同。
$(".themeChanger").click(function () {
alert($(this).attr("data-themeValue"));
alert($(this).data("themeValue"));
});
<button class="themeChanger" data-themeValue="Theme1" data-theme-value="Theme2"></button>
$(".themeChanger").click(function() {
var el = $(this);
alert($(this).data("themeValue")); //Theme2
alert($(this).data("themevalue")); //Theme1
});
<button type="button" class="themeChanger" data-theme-value="grid" value="Grid">
data-theme-value
</button>
<button type="button" class="themeChanger" data-themeValue="grid" value="Grid">
data-themeValue
</button>
$(".themeChanger").click(function () {
alert($(this).attr("data-themeValue"));
alert($(this).data("themeValue"));
});