jquery - 匹配 JQuery 中的确切字符串
问题描述
例如,我有以下文本:
- 绿色棒球帽
- 卡纳维拉尔角
我想用字符串 Cap 过滤结果。我现在拥有的是检查字符串是否包含 asubstring
但我想匹配实际单词。这就是我现在所拥有的
$('#filter').click(function() {
...
// Filters items based on the search criterias.
$('figure.col-sm-3')
.has('tr:last-child>td:last-child:contains(' + month + ')')
.has('tr:last-child>td:last-child:contains(' + year + ')')
.has('h6:contains(' + brand + ')')
.has('h6:contains(' + type + ')')
.has("tr.price td:nth-child(even)")
.each(function(index, self) {
var price = $(self).find("tr.price td:nth-child(even)").eq(0).text();
arr.push(price);
totalPrice += parseFloat( price );
});
...
});
解决方案
您可以创建一个自定义伪选择器,如下所示:hasword
或使用 filter(function)
在每种情况下,按空格分割文本并查看结果数组是否包含所需的单词
const word = 'Cap';
$.expr[':'].hasword = function(elem, i, match) {
const words = $(elem).text().trim().split(' ')
return words.includes(match[3]);
}
$('.foo:hasword(' + word + ')').css('color','red');
$('.foo').filter(function(i,elem){
const words = $(elem).text().trim().split(' ')
return words.includes( word)
}).css('background', 'yellow')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo">Green Baseball Cap</div>
<div class="foo">Cape Canaveral</div>
<div class="foo">Cap</div>
<div class="foo">Cape</div>
推荐阅读
- javascript - websocket连接失败
- angular - 角度 11 无法绑定到“允许”,因为它不是“iframe”的已知属性
- google-cloud-platform - 云组实例、云 vm 实例
- javascript - 使用 THREEjs 加载纹理的提升问题
- python - numpy errstate 属性的正确替代方法是什么?
- javascript - 如何取消选中属性选择的复选框
- java - Java Swing Windows 10 外观和感觉
- .net-core - 正确实现 Azure 函数应用的后台工作程序
- python - 为什么我的 except 块被跳过了?
- neovim - 如何在 coc explorer neovim 中显示点文件?