如何检测页面文本触发词并为对应div添加类
实现触发词检测并为父元素添加类的jQuery方案
需求说明
遍历页面中.parent-div下的.phrase元素,检测其文本是否包含指定触发词数组中的任意词汇;若匹配成功,为对应的.parent-div添加自定义类。
完整实现代码
JavaScript(jQuery)
let triggers = [ "hello", "fint", "wasssup", "city", "apple" ]; $('.parent-div .phrase').each(function() { // 获取当前元素文本并转为小写,消除大小写敏感问题 const elementText = $(this).text().toLowerCase(); // 检查是否存在匹配的触发词 const hasMatchingTrigger = triggers.some(trigger => { return elementText.includes(trigger.toLowerCase()); }); if (hasMatchingTrigger) { // 找到最近的.parent-div父元素并添加类 $(this).closest('.parent-div').addClass('trigger-match'); } });
HTML(沿用你的结构)
<div class="container"> <div class="parent-div"><p class="phrase"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took</p></div> <div class="parent-div"><p class="phrase"> city of Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took</p></div> <div class="parent-div"><p class="phrase"> Lorem Hello world Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took</p></div> </div>
可选样式(用于直观展示匹配效果)
.trigger-match { border: 2px solid #ff4444; background-color: #fff5f5; padding: 8px; }
关键逻辑说明
- 大小写兼容处理:把元素文本和触发词都转为小写,确保"Hello"能匹配数组中的"hello",避免大小写导致的匹配失败。
- 高效匹配检测:使用
Array.some()方法遍历触发词数组,只要找到一个匹配项就停止遍历,比循环所有词更高效。 - 精准定位父元素:用
closest('.parent-div')找到当前.phrase元素最近的父级.parent-div,不会误操作其他无关的.parent-div。
进阶优化:精确匹配完整单词
如果需要避免部分匹配(比如不想让"city"匹配"cityscape"),可以改用正则表达式实现完整单词匹配:
const hasMatchingTrigger = triggers.some(trigger => { // \b 表示单词边界,i 表示不区分大小写 const wordRegex = new RegExp(`\\b${trigger}\\b`, 'i'); return wordRegex.test($(this).text()); });
内容的提问来源于stack exchange,提问作者Владимир Солёный
相关产品推荐
相关产品推荐

