简体   繁体   English

使用查找数据属性添加类

[英]Use find data attribute to add class

I am attempting to create a menu with unique data attributes attached to each navigation item. 我正在尝试创建一个菜单,该菜单具有附加到每个导航项的唯一数据属性。 On click I want that navigation item to find the section with the same attribute and add a class to it. 单击时,我希望该导航项找到具有相同属性的部分,并向其中添加一个类。 This is the code I am using thus-far (it is part of a much larger script). 这是到目前为止我正在使用的代码(它是一个更大的脚本的一部分)。

var $el = $( '#bl-main' ),
$sections = $el.children( 'section' ),
$navItems = $( 'nav > a' );   


$navItems.on( 'click', function( event ) {

$el.addClass( 'bl-expand-item' );
$navItems.find("[data-section='" + current + "']");
$sections.find("[data-section='" + $navItems + "']").addClass( 'expand expand-top' );
} );

This is the script it based off of. 这是它基于的脚本。 http://tympanus.net/Development/FullscreenLayoutPageTransitions/ http://tympanus.net/Development/FullscreenLayoutPageTransitions/

The idea is to add a separate floating navigation to link to the different sections (instead of the direct click to expand that is current implemented). 这个想法是添加一个单独的浮动导航来链接到不同的部分(而不是当前实现的直接单击展开)。 The current script I added only seems to refresh the page on click. 我仅添加的当前脚本似乎在单击时刷新了页面。 I couldn't get it to work in a fiddle at all so the original script im sure will work. 我根本无法使它发挥作用,因此原始脚本肯定会起作用。 The section pasted about I have added in on my local files. 关于我粘贴的部分已添加到本地文件中。

On the first line, when you try to call for a <section> element, you are missing the jQuery shorthand before the parentheses. 在第一行上,当您尝试调用<section>元素时,括号前缺少jQuery速记。 That should fix your script. 那应该修复您的脚本。

So it should look like: 所以它应该看起来像:

var $section = $('section');

That should have you all set to continue! 那应该让所有人都继续!

First off you are missing your $ in the first variable assignment. 首先,您在第一个变量赋值中缺少$。 var $section = $('section') var $ section = $('section')

After that it is difficult to tell what you're trying to do without seeing your markup, but I'll take a stab at it. 此后,很难在不看到标记的情况下分辨出您要做什么,但是我会对其进行尝试。

It appears that you are trying to filter the $section object by the data-section attribute of the nav > a element. 看来您正在尝试通过nav>元素的data-section属性过滤$ section对象。 This code should do just that: 这段代码应该做到这一点:

var $section = $( 'section' ), $navItems = $( 'nav > a' );   

$navItems.on( 'click', function( event ) {
    var $navSection = $section.filter("[data-section='" + $( this ).data( 'section' ) + "']");
    $navSection.addClass( 'expand expand-top' );
    return false;
} );

Notice that we are filtering all of the sections by the value of the clicked anchor's data-section attribute. 注意,我们正在通过单击锚点的data-section属性的值来过滤所有部分。

If that doesn't help, add your markup so we can see your structure. 如果这样做没有帮助,请添加您的标记,以便我们可以看到您的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM