Jquery data方法返回undefined和data名称问题

用data自定义属性来获取图片url时发现一直输出undefined,检查了好多遍发现代码没有问题,所以就开始怀疑data书写方式有问题了。

问题:data-命名时我在命名里有大写字母,
解决:
方法1:
data- 后面不要用大写字母,如,

data自定义属性说明

方法2:这样命名 data-xxx-xxx
书写:

data自定义属性说明

获取:$(“div”).data(“attrValue”);

举个栗子:

<html>
<head>
<script type="text/javascript" src="jquery-3.1.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    
    
  $("#btn2").click(function(){
    
    
    console.log($("div").data("largeimg"));
    console.log($("div").data("smallImage"));

  });
});
</script>
</head>
<body>
<button id="btn2">获取 div 元素的数据</button>
<!-- data-后面不能带有大写字母 -->
<div class="item active" data-largeimg="../images/slide_01_2000x410.jpg" data-small-image="../images/slide_01_640x340.jpg">
  <!-- 非移动端  背景图片 -->   
</div>
</body>
</html>

输出:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45295262/article/details/107475138