jQuery 按文本选择链接(完全匹配)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6673777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select link by text (exact match)
提问by Endy Tjahjono
Using jQuery, I want to select a link that contains exactly some kind of text. For example:
使用 jQuery,我想选择一个包含某种文本的链接。例如:
<p><a>This One</a></p>
<p><a>"This One?"</a></p>
<p><a>Unlikely</a></p>
I have tried this:
我试过这个:
$('a:contains("This One")')
But it picks the first AND the second link. I just want the first link, which contains exactly "This One". How can I do that?
但它选择第一个和第二个链接。我只想要第一个链接,它完全包含“This One”。我怎样才能做到这一点?
回答by FishBasketGordo
You can do this:
你可以这样做:
$('a').filter(function(index) { return $(this).text() === "This One"; });
Reference: http://api.jquery.com/filter/
回答by Narnian
A coworker of mine extended jQuery with a function to do this:
我的一个同事用一个函数扩展了 jQuery 来做到这一点:
$.expr[':'].textEquals = function(a, i, m) {
return $(a).text().match("^" + m[3] + "$");
};
The result is that you can select something by exact text this way:
结果是您可以通过这种方式按精确文本选择内容:
$("label:textEquals('Exact Text to Match')");
This makes it easy, since you don't have to remember the exact syntax each time. His entire post is here: jQuery Custom Selector for selecting elements by exact text :textEquals
这很容易,因为您不必每次都记住确切的语法。他的整篇文章在这里: jQuery 自定义选择器用于按精确文本选择元素:textEquals
回答by djhansel
To expand on FishBasketGordo's answer. If you are trying to make the selection on a large amount of elements, use :contains()
first to narrow down and then apply the filter.
扩展 FishBasketGordo 的答案。如果您尝试对大量元素进行选择,:contains()
请先使用缩小范围,然后再应用过滤器。
This will improve the overall speed:
这将提高整体速度:
$('a:contains("This One")').filter(function(index)
{
return $(this).text() === "This One";
});
回答by Archer
had to modify Nariman's solution to be:
不得不将 Nariman 的解决方案修改为:
$.expr[':'].textEquals = function(a, i, m) {
var match = $(a).text().match("^" + m[3] + "$")
return match && match.length > 0;
}
Otherwise didn't work on chrome (Linux)
否则在 chrome (Linux) 上不起作用
回答by Alvis
I was using the extension
我正在使用扩展程序
$.expr[':'].textEquals
But I have found that the implementation no longer works with jQuery 1.7 (apparently a change in Sizzla.filter). After struggling for some time to make it work I have simply written a jQuery plugin to accomplish the same.
但我发现该实现不再适用于 jQuery 1.7(显然是 Sizzla.filter 中的更改)。经过一段时间的努力使其工作后,我简单地编写了一个 jQuery 插件来完成相同的工作。
$.fn.textEquals = function (text) {
var match = false;
$(this).each(function () {
if ($(this).text().match("^" + escapeRegex(text) + "$")) {
match = true;
return false;
}
});
return match;
};
Use:
用:
$(".ui-autocomplete li").textEquals('Exact Text to Match');
Just wanted to share, in case someone else runs into this (,
只是想分享一下,以防其他人遇到这个(,
回答by bwest87
So Narnian's answer works pretty well. Using it in the wild, however, I ran into some issues, where things that I would have expected to get found were not getting found. This was because sometimes there is random white space surrounding the element's text. It is my belief that if you're searching for "Hello World", you would still want it to match " Hello World ", or even "Hello World \n". Thus, I just added the "trim()" method to the function, which removes surrounding whitespace, and it started to work better. Also, I modified the variable names to be a little clearer to my mind.
所以纳尼亚的答案很有效。然而,在野外使用它时,我遇到了一些问题,我期望找到的东西没有找到。这是因为有时元素的文本周围会有随机的空白。我相信,如果您正在搜索“Hello World”,您仍然希望它匹配“Hello World”,甚至“Hello World \n”。因此,我只是在函数中添加了“trim()”方法,它删除了周围的空白,它开始工作得更好。此外,我修改了变量名称,让我的想法更清晰一些。
Specifically...
具体来说...
$.expr[':'].textEquals = function(el, i, m) {
var searchText = m[3];
var match = $(el).text().trim().match("^" + searchText + "$")
return match && match.length > 0;
}
And secondary note... trim only removes whitespace before and after the searched text. It does not remove whitespace in the middle of the words. I believe this is desirable behavior, but you could change that if you wanted.
次要注意...修剪仅删除搜索文本前后的空格。它不会删除单词中间的空格。我相信这是可取的行为,但如果你愿意,你可以改变它。
回答by Michael Khalili
$('a:contains("This One")')[0];
I feel like I'm missing something based on everyone else's answer to filter but why not just select the first item within the array of elements that's returned by 'contains'?
我觉得我根据其他人的过滤答案遗漏了一些东西,但为什么不只选择“包含”返回的元素数组中的第一项?
This works, only if you know that the first link has the exact match you're looking for. Other answers work better, if you're not sure which order the links will be in.
这有效,只有当您知道第一个链接与您正在寻找的完全匹配时。如果您不确定链接的顺序,其他答案会更好。
回答by Vikas Gautam
Sorry, if this exactly matches anybody's answer above,
对不起,如果这与上面任何人的答案完全匹配,
$.fn.equalsText = function (text, isCaseSensitive) {
return $(this).filter(function () {
if (isCaseSensitive) {
return $(this).text() === text
} else {
return $(this).text().toLowerCase() === text.toLowerCase()
}
})
}
Here is some output in the Linkedin search result page console.
这是 Linkedin 搜索结果页面控制台中的一些输出。
$("li").equalsText("Next >", false)
[<li class=?"next">?…?</li>?] // Output
$("li").equalsText("next >", false)
[<li class=?"next">?…?</li>?] // Output
$("li").equalsText("Next >", true)
[<li class=?"next">?…?</li>?] // Output
$("li").equalsText("next >", true)
[] // Output
It has case sensitivity support as well and is not using :contains()
它也有区分大小写的支持,并且没有使用 :contains()
Edit (May 22, 2017) :-
编辑(2017 年 5 月 22 日):-
$.fn.equalsText = function (textOrRegex, isCaseSensitive) {
return $(this).filter(function () {
var val = $(this).text() || this.nodeValue
if (textOrRegex instanceof RegExp) {
return textOrRegex.test(val)
} else if (isCaseSensitive) {
return val === textOrRegex
} else {
return val.toLowerCase() === textOrRegex.toLowerCase()
}
})
}
回答by David Fawzy
var link = $('a').filter(function(index) { return $(this).text() === "Availability"; });
$(link).hide();
$(link).removeAttr('href');
回答by Iulia Lucaciu
How to get the selected value from a drop-dwon:
如何从 drop-dwon 中获取选定的值:
$.fn.textEquals = function (text) {
var match = false;
var values="";
$(this).each(function () {
if ($(this).text().match("^" + text + "$")) {
values=$(this).val();
match = true;
return false;
}
});
return values;
};
console.log($("option").textEquals("Option One"));
- it will return the value of the drop-down
console.log($("option").textEquals("Option One"));
- 它将返回下拉列表的值