jquery 过滤器:只获取第一个匹配项?

lau*_*kok 6 css jquery filter jquery-1.9

我想在链接的 url 中找到匹配项,然后对该链接执行一些操作,例如更改它的颜色等。

$("a").filter("[href*='id=10']").css({color: 'red'});
Run Code Online (Sandbox Code Playgroud)

html,

<a href="http://website.come/folder/file.php?id=9&ajax=true">0</a>
<a href="http://website.come/folder/file.php?id=10&ajax=true">1</a>
<a href="http://website.come/folder/file.php?id=20&ajax=true">2</a>
<a href="http://website.come/folder/file.php?id=30&ajax=true">3</a>
<a href="http://website.come/folder/file.php?id=10&ajax=true">11</a>
Run Code Online (Sandbox Code Playgroud)

但是我在链接列表中有两个匹配项,我只想要第一个匹配项。我应该在 jquery 代码中添加什么?

提琴手

Luc*_*ems 6

尝试这个 :

$("a").filter("[href*='id=10']").first().css({color: 'red'});
Run Code Online (Sandbox Code Playgroud)

如果你愿意,你也可以这样做:

$("a[href*='id=10']").first().css({color: 'red'});
Run Code Online (Sandbox Code Playgroud)

  • 这不会得到每个结果然后返回第一个结果吗?如果你有一百万件东西,性能可能会很差,但如果有两件,这没什么大不了的。 (5认同)