Javascript 如何将类应用于数组中段落标记中的所有单词?
假设我有一段定义为Javascript 如何将类应用于数组中段落标记中的所有单词?,javascript,jquery,dom,text,Javascript,Jquery,Dom,Text,假设我有一段定义为 <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> 如何迭代段落中的每个项目并附加一个 <span color="blu
<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>
如何迭代段落中的每个项目并附加一个
<span color="blue"></span>
围绕blueWords数组中的预定义单词?这在jQuery中可能很容易做到,但我不确定如何做到这一点。您可以尝试以下代码:
$('p').html($('p').html().replace(/(\sparagraph\s|\swords\s|\swhich\s|\sa\s)/ig, '<span style="color: blue">$1</span>'))
它使用Regex替换方法。正则表达式是在字符串中进行搜索的强大方法。这里有一个非jQuery解决方案: 我在你的段落中添加了一个名为“test”的id,并创建了一个名为blue的样式 然后。。。
我更喜欢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);
你试过什么吗?你挂断了什么?您基本上需要将内容加载到一个字符串中,将其拆分为一个数组,循环遍历每个单词,根据需要添加类,然后将所有内容放回一起并将其吐出@ernie这在jQuery中可能很容易做到,但我不确定如何去做。无论如何,jQuery不会让这更简单。文本节点必须被拆分。@Seth我看到了。我的观点是,提问者似乎在要求我们解决他们的问题,而他们自己却没有付出任何努力,这是SO社区普遍不赞成的。如果问题是,jQuery中是否有任何方法可以解析字符串,从而允许逐字比较?或者,关于jQuery的声明可能有用,但即使如此,这也是一个延伸@厄尼我发布了所有这些,但是如果OP不知道如何去做,他怎么去谷歌呢?或者试试什么?是的。这是为了看看我在工作时代码是否正常工作。但是我要更新我的答案。如果我想动态加载一个数组,并且让该数组成为帮助应用该类的数组,该怎么办?例如,我可以发出一个ajax请求并获得一个单词数组,这些单词需要按照我上面指定的方式进行解析。
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>
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);