开发者

How to jQuery select all links on a page that are NOT contained within a certain div

Suppose I have product 开发者_JAVA技巧links on a page, some products are within a recommendation div:

<a href="some_url?pid=abc"><img src ... ></a>
<a href="some_url?pid=abc">ABC Product Name...</a>

<a href="some_url?pid=def">
 .... more product links

<div class="recommendations">
  <a href="some_url?pid=uvw"> ...
  <a href="some_url?pid=xyz"> ...
</div>

I need to construct unique list of pids for recommended and non-recommended urls like this:

 recommended_pids = ["uvw","xyz"];
 non_recommened_pids = ["abc","def"];

I know I can git the list of all pid on a page like this:

 $('a[href*="pid="]').each(function() {
   //get just the pid part
   var link = this.href;
   var pid = link.split('pid=')[1].split('&')[0];
   pids.push(pid);
 });

And I can get the list of recommended pids on a page using selector like this:

$('div.recommended a[href*="pid="]')

Sort and uniq each array then subtract all elements then do array subtraction to get the list of non-recommended pids.

But is there a way to use other jQuery filters to get the list of pids NOT contained within the recommended div without resorting to writing an array subtract function?


Well, there's always .filter():

var $pidLinks = $('a[href*="pid="]');
// recommended links
$pidLinks.filter('div.recommendations > a');
// non-recommended links
$pidLinks.filter(':not(div.recommendations > a)');

Somewhat gratuitous jsFiddle

For what it's worth, @Jayendra's solution is simpler and probably better, unless you need to get both lists - in which case I believe that using .filter() should have better performance if you cache the original selection of all links.


Use not

$("a:not(.recommendations a)").each(function(index){
    alert(this.id);
});


Inside the each function you could do this:

if( $(this).parents(".recommendations").length ) {

    recommended_pids.push(pid);

} else {

    non_recommened_pids.push(pid);

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜