给定多个锚标记:
<a class="myclass" href="...">My Text</a>
如何选择与班级匹配并带有特定文本的锚点。例如,选择所有带有类别“ myclass”和文本:“ My Text”的锚点
Answers:
$("a.myclass:contains('My Text')")
$('a.myclass[href]:contains("My Text")')
如果仅当锚文本包含特定字符串时才感到困扰,请使用@Dave Morton的解决方案。但是,如果您想完全匹配特定的字符串,我建议使用以下方法:
$.fn.textEquals = function(txt) {
return $(this).text() == txt;
}
$(document).ready(function() {
console.log($("a").textEquals("Hello"));
console.log($("a").textEquals("Hefllo"))
});
<a href="blah">Hello</a>
略有改进的版本(带有第二个修整参数):
$.fn.textEquals = function(txt,trim) {
var text = (trim) ? $.trim($(this).text()) : $(this).text();
return text == txt;
}
$(document).ready(function() {
console.log($("a.myclass").textEquals("Hello")); // true
console.log($("a.anotherClass").textEquals("Foo", true)); // true
console.log($("a.anotherClass").textEquals("Foo")); // false
});
<a class="myclass" href="blah">Hello</a>
<a class="anotherClass" href="blah"> Foo</a>
首先,选择所有包含“ MY text”的标签。然后,对于每个精确匹配,如果匹配条件,则执行您想做的任何事情。
$(document).ready(function () {
$("a:contains('My Text')").each(function () {
$store = $(this).text();
if ($store == 'My Text') {
//do Anything.....
}
});
});