【问题标题】:Variable inside a String inside a String字符串内的变量 字符串内的变量
【发布时间】:2013-04-12 23:05:06
【问题描述】:

当我尝试将一个变量放入一个已经在字符串中的字符串中时,我遇到了一个小问题。基本上,我正在尝试使用颜色变量(字符串,例如“#FF0”)更改特定单词的颜色。这就是替换函数的样子:

$('#textWithTheWord').replaceWith($('<div></div>').append($('#textWithTheWord').clone()).html().replace(word, '<span style="color:red;">' + word + '</span>'));

请注意,我想用该变量替换 '&lt;span style="color:red;"&gt;' 中的“红色”。 提前致谢!

【问题讨论】:

  • 如果我理解正确的话,#textWithTheWord 是一个 element,其中包含一个 span,其中有一个内联 style 属性来设置 color。然后,您要修改该 span 元素的 color 值。那正确吗?如果是这样的话,你有什么理由想通过操作字符串来做到这一点?
  • @plalx 是的,到目前为止,你是对的。我试图更改特定单词的颜色,我找到的唯一解决方案是:link
  • 我已经发布了您的问题的答案,希望对您有所帮助。好运! ;)
  • 这肯定有助于让我的代码看起来更“智能”! :) 但是我仍然有颜色变量,它可以改变,我正在思考如何改变颜色。
  • @felixfritz,我很高兴能帮上忙!很高兴您花时间了解事情是如何完成的,这样您就可以针对您的需求制定解决方案。干杯! ;)

标签: javascript string variables


【解决方案1】:

一个简单的解决方案是简单地将元素的innerHTML 属性替换为一个新的html 字符串,该字符串会将单词包装在span 中。但是,这不是一个非常灵活的解决方案,因为通过替换 innerHTML 属性,所有元素都将被更新,这可能会产生意想不到的结果,除非您定位仅包含文本节点的元素。

假设body 包含以下文本:

this is some text and I want to replace the word cool

你可以:

var $body = $(document.body);

$body.html($body.html().replace(/\b(cool)\b/g, '<span style="color: red;">$1</span>'));

这里/\b(cool)\b/g 正则表达式将匹配每个cool 单词并在它们上创建一个捕获组,允许我们在替换表达式中将其引用为$1

但是,最先进的解决方案可能会像这样实现:

  • 循环遍历不包含在具有data-styled-text 属性的span 中的文本节点。 (您可以查看textNode.parentNode 属性)
  • &lt;span data-styled-text&gt; 标记将您想要的词括起来。看看https://developer.mozilla.org/fr/docs/DOM/Text.splitText
  • 查询所有&lt;span data-styled-text&gt; 元素并对它们进行任何操作。

我玩弄了这个概念,并为您创建了一个小提琴,展示了如何使用regex 以任何方式操作文本以定位特定文本。我创建了 2 个主要功能 wrapTextstyleText,这将允许您对页面上的文本执行任何操作。它可以进一步优化,但你会明白的。

看看http://jsfiddle.net/scarsick/tX4Ge/1/

以下函数允许您将任何文本包装在文本节点中。

function wrapText(textNode, textRx, wrapFn) {
    var global = textRx.global,
        wrapEl,
        result, 
        rightTextNode,
        matchedText,
        index;

    while (result = textRx.exec(textNode.nodeValue)) {
        rightTextNode = textNode.splitText(index = result.index);
        rightTextNode.nodeValue = rightTextNode.nodeValue.substring((matchedText = result[0]).length);
        wrapEl = wrapFn(matchedText, index);
        wrapEl.appendChild(document.createTextNode(matchedText));
        rightTextNode.parentNode.insertBefore(wrapEl, rightTextNode);

        if (!global) {
            break;
        }

        textNode = rightTextNode;
        textRx.lastIndex = 0;
    }    
}

以下函数允许您为元素中包含的任何文本设置样式。

function styleText(el, textRx, styleFn) {
    var wrapEl = document.createElement('span'),
        slice = [].slice;

    wrapEl.setAttribute('data-styled-text', 'true');

    styleText = function(el, textRx, styleFn) {
        var childNodes = slice.call(el.childNodes, 0),
            i = 0,
            len = childNodes.length,
            node;

        for (; i < len; i++) {
            node = childNodes[i];

            switch (node.nodeType) {
                case 3:
                     if (!node.parentNode.getAttribute('data-styled-text')) {
                         wrapText(node, textRx, function (text, index) {
                             var el = wrapEl.cloneNode();

                             styleFn(el, text, index);

                             return el;
                         });

                         continue;
                    }

                    styleFn(node.parentNode);
                    break;
                case 1:
                    styleText(node, textRx, styleFn);
                    break;
            }
        }
    };

    styleText(el, textRx, styleFn);
}

【讨论】:

    【解决方案2】:

    如果所有这些代码的存在只是为了改变元素中文本的颜色,你可以像这样大大简化它:

    var color = "#ff8877";
    $('#textWithTheWord').css('color', color);
    

    http://api.jquery.com/css/

    无需使用 DOM 或字符串连接来更改元素的属性或样式。 jQuery 可能会有一个功能可以满足您的需求。

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 1970-01-01
      • 2018-02-05
      • 2015-11-01
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 2022-01-14
      • 2017-06-21
      相关资源
      最近更新 更多