在jQuery中,我们可以使用选择器来查找DOM元素,特别是当需要基于元素的内容进行筛选时。要从多个<span>
元素中选择包含特定文本并且具有特定类的元素,我们需要结合使用jQuery的类选择器和内容过滤方法。
:contains()
选择器// 选择所有包含"特定文本"且具有"target-class"类的span元素
$('span.target-class:contains("特定文本")').css('background-color', 'yellow');
.filter()
方法// 选择所有具有"target-class"类的span元素,然后过滤出包含"特定文本"的
$('span.target-class').filter(function() {
return $(this).text().indexOf('特定文本') >= 0;
}).css('color', 'red');
如果需要精确匹配文本(而非包含):
$('span.target-class').filter(function() {
return $(this).text().trim() === '特定文本';
}).addClass('highlight');
<!DOCTYPE html>
<html>
<head>
<title>jQuery Span Text Selection</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<span class="target-class">Hello World</span>
<span class="target-class">jQuery is awesome</span>
<span class="other-class">Hello World</span>
<span class="target-class">Hello World again</span>
<script>
$(document).ready(function() {
// 方法1:使用:contains
$('span.target-class:contains("Hello World")').addClass('highlight');
// 方法2:使用.filter()
$('span.target-class').filter(function() {
return $(this).text().trim() === 'Hello World';
}).css('border', '1px solid red');
// 统计包含"Hello"的target-class span数量
var count = $('span.target-class').filter(function() {
return $(this).text().indexOf('Hello') >= 0;
}).length;
console.log('Found ' + count + ' matching elements');
});
</script>
</body>
</html>
:contains()
选择器是大小写敏感的.text()
方法获取纯文本内容以上方法可以根据具体需求选择使用,:contains()
更简洁但.filter()
提供了更精确的控制能力。
没有搜到相关的沙龙