jquery - 为什么 .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>
我期待日志中有一个字符串,但每次都未定义。
解决方案
$('[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”开头,它被选为父元素。它可能没有任何数据事件属性,因此显示未定义。您可能希望您的选择器尽可能具体以排除这种情况。
推荐阅读
- javascript - 编辑 fullRow 时,Ag-grid 编辑似乎不尊重 rowHeight
- vba - 具有各种标准的 VBA 循环
- getstream-io - 使用 getstream.io 避免不同提要中的重复
- python - 我的代码测试没有通过我的冒泡排序算法
- reactjs - Redux 在开发中工作,似乎在生产中中断
- python - 使用 django 应用程序的 Cron 作业
- ethereum - 使用solidity创建合约但不执行
- scala - 如何在 spark 中的 windows 上制作更快的窗口文本文件和机器学习
- macros - 如何在 SAS Guide 中计算存活率?
- regex - IP 地址的 Hive 正则表达式