检查
.length
结果jQuery集合的:
const len = $('table td').filter(function() {
return $(this).text() === text;
}).length;
if (len > 0) {
console.log('text found');
}
但使用类似这样的方法可能更合适
some
const text = 'foo';
const spanExists = Array.prototype.some.call(
$('table td'),
td => $(td).text() === text
);
if (spanExists) {
console.log('text found');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>foo</td>
</tr>
</table>
关于你的编辑,问题是你的
"table td:contains(" + text + ")"
不止一个元素
text
是
foo
,都是第二个
tr
tr公司
因为两者都包含
福
. 然后,用
.text()
,的文本
二者都
td
associatedPrice
:
获取匹配元素集中每个元素的组合文本内容
因为你不仅需要检查
td公司
td公司
是的,你可以用
Array.prototype.find
Array.prototype.some
-
.find
将返回找到的元素(如果有),而不仅仅返回布尔值。
$("a.product-title").each(function() {
const text = $(this).text();
const td = Array.prototype.find.call(
$('table td'),
td => $(td).text() === text
);
if (td) {
var associatedPrice = $(td).next('td').text();
$(this).closest('.simple-product-tile')
.find(".lbl-price")
.replaceWith(associatedPrice);
}
});
table {
background: red;
color: white;
}
.simple-product-tile {
padding: 10px;
}
.product-title {
background-color: #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="simple-product-tile">
<a class="product-title">unique</a>
<span class="lbl-price">Loading...</span>
</div>
<div class="simple-product-tile">
<a class="product-title">foo</a>
<span class="lbl-price">Loading...</span>
</div>
<div class="simple-product-tile">
<a class="product-title">foo 2</a>
<span class="lbl-price">Loading...</span>
</div>
<br><br>
<table>
<tr>
<td>unique</td>
<td>1.99</td>
</tr>
<tr>
<td>foo</td>
<td>1.99</td>
</tr>
<tr>
<td>foo 2</td>
<td>2.99</td>
</tr>
</table>