I'm not able to find anchor element by it's exact text content
我无法通过它的确切文本内容找到锚元素
HTML
<a href="javascript:void(0);">Project One</a>
<a href="javascript:void(0);">Project</a>
JS
var vInput = "Project";
alert($("a:contains('" + vInput + "')").length);
Output
2
I want the output to be 1
. Is there any way that I can match only the anchor element with the text Project
NOT Project One
?
我希望输出为1.有没有什么方法可以只使用文本Project NOT Project One匹配锚元素?
3 个解决方案
#1
You can use filter()
function and check if the text matches the desired string:
您可以使用filter()函数并检查文本是否与所需的字符串匹配:
alert($('a').filter(function() {
return $(this).text() == 'Project';
}).length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="javascript:void(0);">Project One</a>
<a href="javascript:void(0);">Project</a>
#2
You can use .filter() for matching the exact content as :contains() will return partial matches
您可以使用.filter()来匹配确切的内容:contains()将返回部分匹配
var vInput = "Project";
var $as = $('a').filter(function() {
return vInput == $(this).text().trim()
})
alert($as.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0);">Project One</a>
<a href="javascript:void(0);">Project</a>
#3
USe filter
var vInput = "Project";
var anchors = $("a").filter(function() {
return $(this).text().trim() == vInput;
});
alert(anchors.length);
#1
You can use filter()
function and check if the text matches the desired string:
您可以使用filter()函数并检查文本是否与所需的字符串匹配:
alert($('a').filter(function() {
return $(this).text() == 'Project';
}).length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="javascript:void(0);">Project One</a>
<a href="javascript:void(0);">Project</a>
#2
You can use .filter() for matching the exact content as :contains() will return partial matches
您可以使用.filter()来匹配确切的内容:contains()将返回部分匹配
var vInput = "Project";
var $as = $('a').filter(function() {
return vInput == $(this).text().trim()
})
alert($as.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0);">Project One</a>
<a href="javascript:void(0);">Project</a>
#3
USe filter
var vInput = "Project";
var anchors = $("a").filter(function() {
return $(this).text().trim() == vInput;
});
alert(anchors.length);