如何使用每个文章过滤attr href中的文章并查找用法? 简单的标签列表

我有很多div.articles和那篇文章; 我有标签列表。 我正在尝试隐藏文章div,但没有得到href =’#myFilter’。

到达href我没有问题,我的问题是在没有创建jQuery冲突的情况下达到它的parent()。

这是jsFiddle示例来检查。

jQuery的

//trying to hide which don't got a href '#/news' var news = '#/news'; $('.article a').each(function() { var category = $(this).attr('href'); if ( category === news ) {//select only articles got #/news href in it //$(this).parent().parent().parent().show();//trying to reach article $(this).show(); }else{ //$(this).parent().parent().parent().hide();//this way hides all articles $(this).hide();//this works only on a elements } });​ 

HTML:

 

对于每篇文章,使用闭包来跟踪是否应该隐藏当前项目。 这不会有nbrooks答案的闪烁。

正如这个小提琴所示: http : //jsfiddle.net/878zQ/14/

 var news = '#/news'; var nature = '#/nature'; var sport = '#/sport'; var hobbies = '#/hobbies'; var economy = '#/economy'; var world = '#/world'; $('.article').each(function() { var hide = 1; $(this).find('a').each(function() { var category = $(this).attr('href'); if (category == news) { hide = 0; } }); if (hide == 1) $(this).hide(); }); 

为了解释这一点,这里是function的英文描述:

 For each page element containing a class of article. Set the hide flag to true For each a element in this page element Look at the href attribute and see if it matches the variable news If it does set the hide variable to false. If the hide flag is true hide this element. 

更新 :新演示: http : //jsfiddle.net/9GErB/这消除了您之前看到的闪存,并演示了如何更改选择器以使用变量。 依赖于jQueryfilter方法 ,这正是您的问题所需要的。

 var news = '#/news'; var nature = '#/nature'; var sport = '#/sport'; var hobbies = '#/hobbies'; var economy = '#/economy'; var world = '#/world'; $('.article').filter(function() { return $(this).find('a[href="'+news+'"]').length==0; }).hide(); 

这会将文章集减少到与filter表达式匹配的那些,然后隐藏它们。 这比迭代文章然后迭代每篇文章中的链接要有效得多。


更新:工作演示http://jsfiddle.net/WfdXE/

使用jQuery的.closest()方法获取与某个选择器匹配的dom树中最近的祖先。

 $('.article').hide(); $('.article').find('a[href="#/news"]').each(function() { $(this).closest('.article').show(); }); 

jQuery属性选择器是[name="value"]

要在此处使用字符串变量,您可以这样做:

 var sel = "myFilter"; .find('a[href="'+sel+'"]') // this simply includes the text value of sel as the value 

在JS中,您使用+进行字符串连接。

试试这个,

现场演示

 $('.article').each(function() { $(this).find('a').each(function(){ if ( $(this).attr('href') === news ) { $(this).closest('.article').show(); return false; }else $(this).closest('.article').hide(); }); });​