简体   繁体   中英

jquery - selecting class with specific data-attribute value

Having a bit of a dumb moment right now and can't figure out why this is not working. It's been awhile since doing anything with jquery.

var owl = $('.owl-main');
var button = $('.owl-button');

owl.owlCarousel({
    dots:false,
    margin:15,
    nav:true,
    navText: [
        '<span class="o-page">Prev</span>',
        '<span class="o-page">Next</span>'
    ],
    responsive:{
        0:{
            items:1
        }
    },
    onChanged: callback
})

function callback(event) {
    console.log(event.item.index);
    console.log(button);

    button.removeClass('active');
    //$(".owl-button[data-id='"+event.item.index+"']").addClass('active');
    button.find("[data-id='" + event.item.index + "']").addClass('active');
}

My issue is button.find("[data-id='" + event.item.index + "']").addClass('active'); does not add the 'active' class yet the commented out code above it, $(".owl-button[data-id='"+event.item.index+"']").addClass('active'); works perfectly fine.

button and event.item.index are reporting correctly so why is that particular line doing nothing for me?

The issue is find() .. You are using it the wrong way.. it will actually search for the child element within the button with the given attribute. But what you want is to find a button with the given attribute.

  • The commented code is the way you have to do it.

Edit: If you want to use the stored array of button itself to get this working then you can use filter() in place of find

Here is a reference http://api.jquery.com/filter/

button.filter("[data-id='" + event.item.index + "']").addClass('active');

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