如何将类应用于数组中段落标记中的所有单词

How can I apply a class to all words in a paragraph tag which are in an array?

本文关键字:单词 段落标 应用于 数组      更新时间:2023-09-26

假设我有一段定义为

<p>Here is a short paragraph of text which has repeating words. Words such <br>
as these will have a span around them which changes a property of words in a <br>
paragraph.
</p>

有一个脚本,它有一个单词数组,我想把这个类应用到其中

var blueWords = ["paragraph", "words", "which", "a"];

如何迭代段落中的每个项目并附加

<span color="blue"></span>

围绕blueWords数组中的预定义单词?这在jQuery中可能很容易做到,但我不确定如何做到这一点。

这里有一个非jQuery解决方案:

我在你的段落中添加了一个名为"test"的id,并创建了一个称为blue的样式。

然后。。。

    var ParagraphText = document.getElementById('test').innerHTML;
    var blueWords = ["paragraph", "words", "which", "a"];
    function MakeWordsBlue(ParagraphText, blueWords) {
        var i = 0;
        for (i = 0; i < blueWords.length; i++) {
            ParagraphText = ParagraphText.replace(blueWords[i], '<span class="blue">' + blueWords[i] + '</span>')    
        };
        document.getElementById('test').innerHTML = ParagraphText;
    };
    MakeWordsBlue(ParagraphText, blueWords);
</script>

我更喜欢RegExp的答案。但是,一个循环也可以做到这一点:

var blueWords = ["paragraph", "words", "which", "a"],
text = $('#mytext').text().split(' '),
outputStr = "";
for(i=0;i<text.length;i++) {
    if (blueWords.indexOf(text[i]) >= 0) {
        outputStr += '<span class="blue">' + text[i] + '</span> ';
    }
    else outputStr += text[i] + ' ';
}
$('#mytext').html(outputStr);

(http://jsfiddle.net/ajK7B/)

您可以尝试以下代码:

$('p').html($('p').html().replace(/('sparagraph's|'swords's|'swhich's|'sa's)/ig, '<span style="color: blue">$1</span>'))

它使用Regex的替换方法。Regex是在字符串中进行搜索的一种强大方法。