首页 > 解决方案 > 为什么 .data() 和 .attr() 返回 undefined 虽然数据属性名称匹配?

问题描述

单击 div 时,我想将数据属性中的变量传递给 JS 文件。

我试过了$(this).data('event')$(this).attr('data-event')但都返回未定义。

<div id="event{$event['id']}" data-event="{$event['id']}">
<span>{$event['name']}</span>
</div>
$('[id^="event"]').on('click', function(e) {
    console.log($(this).data('event'));
    console.log($(this).attr('data-event'));
});
//browser output
<div class="m-widget4 event-click" id="event2" data-event="2">
 <div class="m-widget4__item">
  <div class="m-widget4__ext">
   <span class="m-widget4__icon m--font-brand m--font-bold">
   Event:
   </span>
  </div>
  <div class="m-widget4__info">
    <button class="m-widget4__text event-click-text">
    Olelele OKsadno saodi.
    </button>
  </div>
 </div>
</div>

Raj 要求的开发人员工具截图。

我期待日志中有一个字符串,但每次都未定义。

标签: jquery

解决方案


$('[data-event]').click(function(e) {
  console.log($(this).data('event'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-widget4 event-click" id="event2" data-event="2">
 <div class="m-widget4__item">
  <div class="m-widget4__ext">
   <span class="m-widget4__icon m--font-brand m--font-bold">
   Event:
   </span>
  </div>
  <div class="m-widget4__info">
    <button class="m-widget4__text event-click-text">
    Olelele OKsadno saodi.
    </button>
  </div>
 </div>
</div>

工作正常 :) 它也适用于[id^="event"],我只是发现这样更方便。

编辑:我能想象到的唯一问题是你可能有另一个元素的 id 以“event”开头,它被选为父元素。它可能没有任何数据事件属性,因此显示未定义。您可能希望您的选择器尽可能具体以排除这种情况。


推荐阅读