繁体   English   中英

jquery - 查找 id 与另一个元素数据属性匹配的元素的最佳方法

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

我在菜单链接列表上使用了 html 的 data- 属性,以便将链接绑定到单击链接时要打开的内容部分的 div id。 因此,如果我有一个名为“#section1”的隐藏 div - 打开该链接的链接是。

目前,为了找到与此链接匹配的 div,我使用 jquery.each() 来遍历所有可能的元素,但似乎应该有更好的方法。

有谁知道我如何简化这段代码并找到匹配的元素而不必循环运行代码?

这是我的代码:

$('a.hidden_link').click(function(){
    section_ident = $(this).attr('data-ident');
    $('.hidden_section').each(function(index) {
        if ($(this).attr('data-ident') == section_ident){
            section_ref = $(this);
            section_ref.show();
        }
    });
});

这应该有效。

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

jsfiddle, http://jsfiddle.net/playrace/H7jwb/

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

全部一起:

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

这听起来像是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();
});

暂无
暂无

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

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