如何 jQuery 选择页面上不包含在特定 div 中的所有链接
假设我在页面上有产品链接,一些产品在推荐 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>
我需要为推荐和非推荐的 url 构建唯一的 pid 列表,如下所示:
recommended_pids = ["uvw","xyz"];
non_recommened_pids = ["abc","def"];
我知道我可以像这样在页面上 git 获取所有 pid 的列表:
$('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);
});
我可以使用这样的选择器获取页面上推荐的 pid 列表:
$('div.recommended a[href*="pid="]')
对每个数组进行排序和 uniq,然后减去所有元素,然后进行数组减法以获得非推荐 pid 列表。
但是有没有办法使用其他 jQuery 过滤器来获取不包含在推荐的 div 中的 pid 列表,而无需编写数组减法函数?
Suppose I have product 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,总有
.filter()
:有些无偿的 jsFiddle
对于值得的是,@Jayendra 的解决方案更简单,而且可能更好,除非您需要获取两个列表 - 在这种情况下我相信使用
.filter()
如果缓存所有链接的原始选择,应该会有更好的性能。Well, there's always
.filter()
: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
在每个函数中你可以这样做:
Inside the each function you could do this: