我有这个按钮:
<button type="button" class="themeChanger" data-themeValue="grid" value="Grid">
<img src="templateImages/Icon_200.png" />
</button>
Run Code Online (Sandbox Code Playgroud)
而这个jQuery:
$(".themeChanger").click(function () {
alert($(this).attr("data-themeValue"));
alert($(this).data("themeValue"));
});
Run Code Online (Sandbox Code Playgroud)
由于某种原因,第一个警报显示"网格"应该像它应该,但第二个警告显示未定义.有什么东西让我感到愚蠢吗?
voi*_*tan 31
我认为数据会看小写: alert($(this).data("themevalue")) //grid
或者如果你想使用themeValue,你需要使用:
编辑:
我错了,它与小箱没有任何关系,如果你有属性你可以使用themeValue:data-theme-value然后用$(element).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
});
Run Code Online (Sandbox Code Playgroud)
JAA*_*lde 24
正如本学习jQuery文章所述,HTML5 data-*属性由浏览器 - > JS转换处理,与处理CSS名称的方式相同 - 即:
data-删除了前导(我上面提到的CSS名称比较中不需要的步骤)
data-specialInfo 变 specialInfodata-more-specialInfo 变 more-specialInfo-
specialInfo 变 [ specialInfo ]more-specialInfo 变 [ more, specialInfo ][ specialInfo ] 变 [ specialinfo ][ more, specialInfo ]成为[ more, specialInfo ](没有变化,因为第一部分已经更低)[ specialinfo ]变得[ specialinfo ](因为没有其他部分没有变化)[ more, specialInfo ] 变 [ more, Specialinfo ][ specialinfo ] 变 specialinfo[ more, Specialinfo ] 变 moreSpecialinfo在这种情况下,您的data-themeValue属性可通过$(this).data("themevalue").而data-theme-value属性可以通过$(this).data("themeValue").
除非您认识到使用的机制,否则它会非常混乱.
问题是骆驼案.为清楚起见,我会坚持data-theme-value你的属性格式.
jquery自动转换.data('some-value')为data('someValue')
请注意,两个警报调用都会返回 grid