开发者

jquery - best way to find an element with an id that matches another elements data attribute

I use html's data- attribute on a list of menu links in order to tie the links to the div ids of sections of content I want to open when the links are clicked. So if I have a hidden div called "#section1" - the link that would open that link is .

Currently, in order to find the div that matches this link, I use jquery .each() to loop through all the possible elements, but it seems like there should be a better way.

Does anybody know how I could streamline this code and find the matching element without having to run the code in a loop?

Here's my code:

$('a.hidden_link').click(function(){
    section_ident = $(this).attr('data-ident');
    $('.hidden_section').each(function(index) {
        if ($(this).attr('data-ident') == section_iden开发者_如何学Got){
            section_ref = $(this);
            section_ref.show();
        }
    });
});


This should work.

$('a.hidden_link').click(function(){
    $(".hidden_section[data-ident='"+$(this).attr('data-ident')+"']").show();
});

Jsfiddle, http://jsfiddle.net/playerace/H7jwb/


$('.hidden_section[data-ident="' + section_ident + '"]').show();

all together:

$('a.hidden_link').click(function(){
    var section_ident = $(this).attr('data-ident');
    $('.hidden_section[data-ident="' + section_ident + '"]').show();
});


This sounds like a job for jQuery.filter()!

$('a.hidden_link').click(function(){
    var section_ident = $(this).data('ident');
    $('.hidden_section').filter(function() {
        return this.attributes["data-ident"] == section_ident;
    }).show();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜