javascript - 为什么我的自定义数据属性不起作用?

标签 javascript jquery html css

<分区>

使用jQuery

console.log($(this).html());
console.log($(this).data('section'));

产量

<a href="#" data-section="allothers" data-sectiontitle="Other Information" style="font-weight: 600; text-decoration: none;">Include Children?</a>

undefined

而且我不确定我做错了什么。 <a>这是一个未排序的列表 <li>标签,但我不确定为什么这很重要。提前致谢!

最佳答案

如你所说,它是<li>附上 <a>

那么应该是:-

console.log($('li a').html());
console.log($('li a').data('section'));

例子:-

console.log($('li a').html());
console.log($('li a').data('section'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li><a href="#" data-section="allothers" data-sectiontitle="Other Information" style="font-weight: 600; text-decoration: none;">Include Children?</a></li>

注意:- 你可以做 $(this).find('a').data('section');也基于您的 HTML 结构。

关于javascript - 为什么我的自定义数据属性不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42586972/

相关文章:

javascript - 向上/向下键盘箭头自动滚动

jquery - 如何使用 jQuery 打开和关闭背景可见性?

javascript - 除非更新表单数据,否则在 Firefox 中禁用表单提交

javascript - 如果特定值,则Angular Template条件语句无法运行

javascript - 提交前进行表单验证的最佳方法是什么

javascript - 焦点事件被另一个焦点事件忽略

javascript - 当我取消选中另一个复选框时自动重新选中一个复选框

javascript - 单击时 Bootstrap 面包屑进入中心 div

javascript - 在 <a> 之前的多个元素之前搜索 <select>

javascript - 达到25个唯一div的末尾后,再加载5个div。 5行,每行5格