我有这段代码:
<nav role="nav" id="primary-nav" class="overview">
<h3 class="section active">
<span class="menu-toggle open"></span>
<span data-content="the-basics">The Basics</span>
</h3>
<ul class="active">
<li><a href="#" class="nav-link" data-content="0">Introduction</a></li>
<li><a href="#" class="nav-link" data-content="1">A Chapter in the Zeitgeist Movement</a></li>
</ul>
<h3 class="section">
<span class="menu-toggle"></span>
<span data-content="setting-up-a-national-chapter">Setting up a National Chapter</span>
</h3>
<ul>
<li><a href="#" class="nav-link" data-content="0">Gathering Volunteers & Social Media</a></li>
</ul>
</nav>
和这个javascript代码
// Load page
$('a.nav-link').on('click', function( event ) {
event.preventDefault();
var $this = $(this);
var parent = this.parentNode;
console.log(parent);
var dataContent = $this.attr("data-content");
console.log(dataContent);
});
获取此特定部分的父H3跨度的data-content =“”的正确方法是什么,例如我想返回The Basics中的“the-basics”
任何建议都非常感激。
答案 0 :(得分:2)
在您给出的示例中,这可能会起作用,但模板更改可能有点脆弱:
$this.closest('ul').prev('h3').children('[data-content]')
答案 1 :(得分:1)
var dataContent = $this.closest('ul').prev('h3').find('span[data-content]').data('content'); // the-basics