如何选择具有完全指定文本的元素

时间:2015-05-07 07:59:08

标签: javascript jquery

我无法通过它的确切文本内容找到锚元素

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);

输出

2

我希望输出为1。有没有什么方法可以只将锚元素与文本Project NOT Project One匹配?

3 个答案:

答案 0 :(得分:1)

您可以使用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>

答案 1 :(得分:0)

您可以使用.filter()来匹配确切的内容,因为:contains()会返回部分匹配

&#13;
&#13;
var vInput = "Project";
var $as = $('a').filter(function() {
  return vInput == $(this).text().trim()
})
alert($as.length);
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用public void removeExistingPeriods() { List<WebElement> removeButtons = driver.findElements(By.cssSelector(".activeLink.removeBtn.btn.btn-warning")); if (removeButtons.size()> 0 && removeButtons.isDisplayed()) { for(WebElement option: removeButtons){ option.click(); } else { fail("No Remove buttons were found on the page!:"); } } }

filter