如何使用jQuery来设置特定单词的所有实例的样式/部分/? [英] How can I use jQuery to style /parts/ of all instances of a specific word?

查看:70
本文介绍了如何使用jQuery来设置特定单词的所有实例的样式/部分/?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不寻常的情况。我有一个客户,我们称之为BuyNow。他们希望他们的网站副本中的每个名称的实例都被样式化,例如购买现在,其中名称的后半部分以粗体显示。

Unusual situation. I have a client, let's call them "BuyNow." They would like for every instance of their name throughout the copy of their site to be stylized like "BuyNow," where the second half of their name is in bold.

我真的很讨厌花一天时间添加< strong>标签到所有副本。有没有一个很好的方法来使用jQuery?

I'd really hate to spend a day adding <strong> tags to all the copy. Is there a good way to do this using jQuery?

我已经看到了jQuery的高亮插件,它非常接近,但我需要大胆的下半部分那个词。

I've seen the highlight plugin for jQuery and it's very close, but I need to bold just the second half of that word.

推荐答案

为了可靠地做到这一点,你必须迭代文档中的每个元素寻找文本节点,并且在那些中搜索文本。 (这是插件在问题中提到的内容。)

To do it reliably you'd have to iterate over each element in the document looking for text nodes, and searching for text in those. (This is what the plugin noted in the question does.)

这是一个允许RegExp模式匹配的纯JavaScript / DOM。由于选择器只能选择元素,因此jQuery并没有给你很多帮助,而且':contains'选择器是递归的,所以对我们来说不太有用。

Here's a plain JavaScript/DOM one that allows a RegExp pattern to match. jQuery doesn't really give you much help here since selectors can only select elements, and the ‘:contains’ selector is recursive so not too useful to us.

// 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, /\bBuyNow\b/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);
});

这篇关于如何使用jQuery来设置特定单词的所有实例的样式/部分/?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆