简体   繁体   English

如何将多个数组项添加为 HTML 内容?

[英]How to add multiple array items as HTML content?

I need to extract some words from a string of text, insert every character of that words inside a span element and then replace the extracted words with the span elements.我需要从文本字符串中提取一些单词,将该单词的每个字符插入 span 元素中,然后用 span 元素替换提取的单词。 I have been able to convert characters into span elements but I can't figure out how to replace the extracted words with the span elements without deleting the other words.我已经能够将字符转换为 span 元素,但我无法弄清楚如何在不删除其他单词的情况下用 span 元素替换提取的单词。

<h1 class="title">Lorem ipsum dolor sit amet</h1>
const title = document.querySelector('.title');

// Extract required words and split them into single character
const firstWord = title.textContent.split(' ').filter(wrd => wrd.startsWith('L')).toString().split('');
const secondWord = title.textContent.split(' ').filter(wrd => wrd.startsWith('a')).toString().split('');

// Return a new array with every character inside a span element
const spanCharacters = arr => {
    return arr.map(char => {
        const span = document.createElement('span');
        span.textContent = char;
        return span;
    });
};

const spanFirstWord = spanCharacters(firstWord);
// return [<span>L</span>, <span>o</span>, <span>r</span>, <span>e</span>, <span>m</span>]

const spanSecondWord = spanCharacters(secondWord);
// return [<span>a</span>, <span>m</span>, <span>e</span>, <span>t</span>]

Now, what I'd like to do is this:现在,我想做的是:

<!-- before -->
<h1 class="title">Lorem ipsum dolor sit amet</h1>

<!-- after -->
<h1 class="title"><span>L</span><span>o</span><span>r</span><span>e</span><span>m</span> ipsum dolor sit <span>a</span><span>m</span><span>e</span><span>t</span></h1>

How could I replace the extracted words with the generated spans keeping the other words where they are?我如何用生成的跨度替换提取的单词,将其他单词保留在原处?

Here is one way to do it:这是一种方法:

 const ttl=document.querySelector("h1.title"), txt=ttl.textContent; function spanifyWords(beginsArr,txt){ return txt.split(" ").map(w=>{ if (beginsArr.some(b=>w.startsWith(b))) w="<span>"+w.split("").join("</span><span>")+"</span>"; return w }).join(" "); } ttl.innerHTML=spanifyWords(["a","L"],txt);
 span {color: green; border:1px solid red}
 <h1 class="title">Lorem ipsum dolor sit amet</h1>

Instead of . filter()而不是. filter() . filter() -ing I use .map() to go through every word. . filter() -ing 我使用.map()到 go 遍历每个单词。 Inside the callback function I check with .some() relative to some beginsArr whether the current word starts with one of the characters in question.在回调 function 中,我检查.some()相对于一些beginsArr当前单词是否以相关字符之一开头。 If so, I "spanify" the word otherwise I return the word as is.如果是这样,我“扩大”这个词,否则我按原样返回这个词。 At the end I stitch everything together again with .join() .最后,我用.join()再次将所有内容缝合在一起。

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

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