如何使用jQuery为特定单词的所有实例的 parts 设置样式?

如何使用jQuery为特定单词的所有实例的 parts 设置样式?,第1张

如何使用jQuery为特定单词的所有实例的/ parts /设置样式?

为了可靠地执行此 *** 作,您必须遍历文档中的每个元素以查找文本节点,然后在其中搜索文本。(这是问题中提到的插件的作用。)

这是一个普通的Javascript /
DOM,它允许RegExp模式匹配。jQuery并没有真正为您提供任何帮助,因为选择器只能选择元素,而’:contains’选择器是递归的,因此对我们来说不太有用。

// Find text in descendents of an element, in reverse document order// pattern must be a regexp with global flag//function findText(element, pattern, callback) {    for (var childi= element.childNodes.length; childi-->0;) {        var child= element.childNodes[childi];        if (child.nodeType==1) { findText(child, pattern, callback);        } else if (child.nodeType==3) { var matches= []; var match; while (match= pattern.exec(child.data))     matches.push(match); for (var i= matches.length; i-->0;)     callback.call(window, child, matches[i]);        }    }}findText(document.body, /bBuyNowb/g, function(node, match) {    var span= document.createElement('span');    span.className= 'highlight';    node.splitText(match.index+6);    span.appendChild(node.splitText(match.index+3));    node.parentNode.insertBefore(span, node.nextSibling);});


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5566474.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存