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

时间:2017-03-03 19:30:28

标签: 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>标记内,但我不确定为什么这一点很重要。提前谢谢!

1 个答案:

答案 0 :(得分:0)

正如你所说,<li>包围了<a>

然后它应该是: -

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

实施例: -

&#13;
&#13;
console.log($('li a').html());
console.log($('li a').data('section'));
&#13;
<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>
&#13;
&#13;
&#13;

注意: - 您也可以根据HTML结构$(this).find('a').data('section');进行操作。

相关问题