Jquery.datareturns“未定义

Jquery .data returns "undefined

我查看了其他帖子,他们的解决方案没有帮助。

我的 HTML 是:

<div class="btn-group">
  <button type="button" class="btn btn-default 1">1</button>
  <button type="button" class="btn btn-default 3">3</button>
</div>

<div class="grid-item grid-item-double-height item-1" data-button-type="interior">
  <a href="#">
    <img src="img/lazyload-ph.png" data-src="img/slurp-004.jpg" class="img-responsive lazyload"/>
  </a>
</div>

而且我尝试了以下 jquery:

$(".btn-group").on('click', 'button', function(e) {
  var push = $(this).data("button-type");
  alert(push);
});

$(".btn-group").on('click', function(e) {
var push = $(this).data("button-type");
alert(push);
});

$(".btn-group").on('click', 'button', function(e) {
  var push = $(this).attr("data-button-type");
  alert(push);
});

我尝试了最后一个,因为我读到使用 "this" 指的是最外层的元素

$("buttn").on('click', function(e) {
  var push = $(this).data("button-type");
  alert(push);
});

$(".btn").on('click', function(e) {
  var push = $(this).data("button-type");
  alert(push);
});

我也尝试过不带 "e",如 :

function(e) {

变成了

function() {

在每种情况下我都会得到 "undefined"。从我所有的研究中我无法弄清楚问题是什么。

谢谢, 理查德·贝洛特

  $(".grid-item").on('click', 'button', function(e) {
      var push = $(this).data("button-type");
      alert(push);
  })

附加到事件侦听器的 class 名称是错误的,在 btn-group classed 中没有使用 data-button-type 属性。

你们真的很亲密。

在 jQuery 中使用 .data() 时,处理方式略有不同。

当您使用时:

$(.someClass).data('myAttribute')

它被jQuery处理为:

<div class='.someClass' data-my-attribute></div>

所以对于你的情况:你可以像下面的代码一样使用它:

$(".btn-group").on('click', 'button', function(e) {
  //this points to the button clicked. So either you use the below code
  //or you should directly select the grid item.
  //This works too
  //var push = $('.grid-item').data("buttonType");
  var push = $(this).parent().siblings('.grid-item').data("buttonType");
  alert(push);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js"></script>
<div class="btn-group">
  <button type="button" class="btn btn-default 1">1</button>
  <button type="button" class="btn btn-default 3">3</button>
</div>

<div class="grid-item grid-item-double-height item-1" data-button-type="interior">
  <a href="#">
    <img src="img/lazyload-ph.png" data-src="img/slurp-004.jpg" class="img-responsive lazyload"/>
  </a>
</div>