繁体   English   中英

根据第一个字母将所有单个单词包装在一个 span 标签中

[英]Wrap all individual words in a span tag based on their first letter

我试图将网页上的每个单词包装在一个标签中,这样我就可以根据它们的首字母分别设置它们的样式。

我发现了这种将每个单词单独包装在 span 标签中的方法,但我不知道如何根据单词的第一个字母来改变 class。

let e = document.getElementById('words');

e.innerHTML = e.innerHTML.replace(/(^|<\/?[^>]+>|\s+)([^\s<]+)/g, '$1<span class="word">$2</span>');

如果您想引用单个单词,则无法使用正则表达式来完成您想要实现的目标。

我写了一个使用document.querySelector()的小片段

查询选择器上的 outerText 属性 object 返回纯文本字符串,稍后使用split()将其转换为数组 function

然后它简单地遍历数组并附加样式标签并获取我使用的第一个字母substring() function

 const words = document.querySelector("#words").outerText.split(" "); const wordsDiv = document.querySelector("#words") wordsDiv.innerHTML = "" words.map((el) => { wordsDiv.innerHTML += `<span class="${el.substring(0, 1)}">${el}</span> ` })
 <div id="words">red green blue orange</div>

尝试这个:

let e = document.getElementById('words');
// Create array with words
let words = e.innerHTML.split(' ');
// Object with CSS classes and corresponding letter
const classes = {
    a: 'class-one',
    b: 'class-two',
    // and so on
}
// Return array with the new strings
words = words.map(word => {
    const firstLetter = word.substring(0,1);
    return `<span class="${classes[firstLetter]}">${word}</span>`;
});
// Join the array and update the DOM
e.innerHTML = words.join(' ');

这里发生了以下情况:

  • 单词被空格分隔,创建一个数组;
  • classes常量必须像示例中那样接收每个字母与其 class 的对应关系;
  • map方法的 function 中,返回单词的第一个字母,并使用该字母访问类 object;
  • 最后,我们进行join以连接所有用空格分隔的文本。

请记住,如果单词之间有多个空格,则会出现不一致,因为第一个字母将是一个空格。

string.prototype.replace引用中,您还可以将替换 function添加到方法中,而不是字符串。 替换 function 具有这种形式

所以,如果我没有误解你的问题,你可以做类似的事情:

let e = document.getElementById('words');

e.innerHTML = e.innerHTML.replace(/(^|<\/?[^>]+>|\s+)([^\s<]+)/g, function(match, p1, p2) {
    const myClasses = {
        a: "aword",
        b: "bword",
        ...
    }
    return `${p1}<span class="${myClasses[p2[0]]}">${p2}</span>'
});

你可以这样做:

  1. Select 全体小朋友
  2. map 他们及其文本内容
  3. 将文本拆分为单个单词
  4. map 再次使用一些样式 html
  5. 加入、渲染和享受。

 words.innerHTML = [...words.children].flatMap(el => el.innerText.replace(/\n/ig, " ").split(" ")).map(el => `<div class="someClass">${el}</div>`).join("")
 .someClass { color: red; background: orange; margin: 10px; }
 <div id="words"> <div> Some dummy content <span>Some other nested dummy content</span> </div> <p>Some sibling content</p> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM