在每个匹配字符串的元素中获取正确的元素

Get right element in each that matches a string

我想使用 .each() 遍历 DOM 个元素并找到具有相同 .text() 作为变量的特定元素。如果正确的元素是最后一个兄弟元素,则会出现问题。

示例:

<p> wrong </p>
<p> wrong </p>
<p> right </p>

在此代码中,在转到正确的元素之前,它会检查两个错误的元素。我无法删除 else,因为我需要查看元素的 none 是否有此文本,如果没有,则应该发生其他事情。现在它将为 false 两次,并将创建 2 个新的 <p>,然后当它到达最后一个元素时,它将抛出 alert()。还有其他方法吗?

$('p').each(function() {
    if ($(this).text() == "right") {
        alert("this exists already");
        return false;
    } else {
        // A p will be created with text right
    }
});

我很确定这就是您要的。

// We care that it exists or not
var already_exists = false;
// Iterate through the existing elements
$('p').each(function() {
    // If it exists, store that and break the loop because we don't need to check any more
    if ($(this).text() == "right") {
        already_exists = true;
        return false;
    }
});

// If, after checking (possibly) all elements, it exists, shout, else create it
if (already_exists){
   alert("this exists already");
}else{
   // A p will be created with text right
}

备注

未经检查,我不确定 <p> right </p> 上的 .text() 是否会匹配“right”,因为 white-space。您可能想要 trim 它。 if ($.trim($(this).text()) == "right")

文本space前后的问题所以请trim你的文本像下面这样

if ($.trim($(this).text())== "right") {}

可以为此使用 filter(),您需要删除空格,否则您的匹配将无法根据所显示的问题进行。

var myVar = 'right';

var exists = $('p').filter(function() {
  return $(this).text().trim() === myVar;
}).length;// length of collection will determine if filter has matches

if(!exists){
   // add element
}

你根本不需要循环。

只需使用 :contains() 选择器。

// alert the user if there is at least one <p>right</p> element
if ($('p:contains("right")').length) {
  alert("this exists already");
  
} else {
  // A p will be created with text right
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> wrong </p>
<p> wrong </p>
<p> right </p>