Javascript jquery—查找id与另一个elements数据属性匹配的元素的最佳方法
我在菜单链接列表上使用html的data-attribute,以便将链接绑定到我希望在单击链接时打开的内容部分的div id。因此,如果我有一个名为“#section1”的隐藏div,那么打开该链接的链接是 目前,为了找到与此链接匹配的div,我使用jquery.each()遍历所有可能的元素,但似乎应该有更好的方法 有人知道我如何简化代码并找到匹配的元素,而不必在循环中运行代码吗 这是我的密码:Javascript jquery—查找id与另一个elements数据属性匹配的元素的最佳方法,javascript,jquery,loops,Javascript,Jquery,Loops,我在菜单链接列表上使用html的data-attribute,以便将链接绑定到我希望在单击链接时打开的内容部分的div id。因此,如果我有一个名为“#section1”的隐藏div,那么打开该链接的链接是 目前,为了找到与此链接匹配的div,我使用jquery.each()遍历所有可能的元素,但似乎应该有更好的方法 有人知道我如何简化代码并找到匹配的元素,而不必在循环中运行代码吗 这是我的密码: $('a.hidden_link').click(function(){ section_
$('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(){
var section_ident = $(this).attr('data-ident');
$('.hidden_section[data-ident="' + section_ident + '"]').show();
});
这应该行得通
$('a.hidden_link').click(function(){
$(".hidden_section[data-ident='"+$(this).attr('data-ident')+"']").show();
});
jshiddle,这听起来像是一份工作
我不确定我是对的,但是你能试试这个$(“#”+节缩进)是不是应该是
section\u ident
?请修正:-)为什么在一步就能完成的情况下,你会找到所有的过滤器?所以在这种情况下,似乎没有理由使用过滤器。今天的第二个问题,在chrome中X更快,在Firefox中Y更快。一定会喜欢的!实际上,在FF5、Chrome和IE9中运行时,使用filter()和自定义函数可以获得更好的性能。只有在FF3.6中,所有的filter()方法都要慢得多。
$('a.hidden_link').click(function(){
$(".hidden_section[data-ident='"+$(this).attr('data-ident')+"']").show();
});
$('a.hidden_link').click(function(){
var section_ident = $(this).data('ident');
$('.hidden_section').filter(function() {
return this.attributes["data-ident"] == section_ident;
}).show();
});