简体   繁体   中英

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/

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. 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')

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. 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.

If that doesn't help, add your markup so we can see your structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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