سؤال

I need to be able to get the href value from the accordion item i just clicked on i assumed this would work (its using twitters collapse plug in)

link:

<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" class="accorLink">

grab it:

$('#accordion').on('show.bs.collapse', function () {
    console.log('foo');
    var sectionID = $(this).attr("href");
    console.log(sectionID);
})

but its not working and just logging "undefined"

am I able to get a value from it ideally the href

هل كانت مفيدة؟

المحلول

The reason its returning undefined is because you're trying to extract an href attribute value that doesn't exist because this refers to the #accordian div.

You can do this by getting the link without the class collapsed:

$('#accordion').on('show.bs.collapse', function () {
    //get the anchor of the accordian that does not has the class "collapsed"
    var openAnchor = $(this).find('a[data-toggle=collapse]:not(.collapsed)');

    //extract the href
    var sectionID = openAnchor.attr('href');
    console.log(sectionID);
});

JSFiddle Demo

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top