3 回答

TA贡献1836条经验 获得超3个赞
我认为你的问题在于check()功能。你已经正确地分析了问题,但是你不了解 DOM 所以你做错了。
首先,你检查的单词是纯字符串(它是一个字符数组,所以你可以用length属性检查它)。其次,它.style.color只是 Element DOM 对象的子对象。字符串不能那样做。
由于这个问题,您必须将刚刚检查的字符串转换为 Element DOM 对象。根据情况,有很多方法可以做到这一点。我假设输出将是这样的:
document.body.innerHTML += word
如果是这样的话,你就可以放心了。只需将 包装word在这个 html 代码字符串中。剩下的你已经很好地解决了。
(我知道你用的是innerText,但我觉得innerHTML更简单,所以我选择了它。如果你真的需要使用innerText,请在下面评论,我会更新帖子)
这是我的代码:
window.onload = function() {
const check = word => {
if (word.length > 8) {
return '<span class="hightlight">' + word + '</span>'
} else {
return word
}
}
const sample = document.querySelector("#sample")
sample.innerHTML = sample
.innerText
.trim()
.split(' ')
.map(check)
.join(' ')
}
#sample {}
.hightlight {
background: yellow
}
<p id='sample'>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
我的建议。在做任何事情之前,试着理解你正在处理的变量的类型。

TA贡献1828条经验 获得超13个赞
window.onload = function() {
check = (word) => {
if (word.length > 8) {
word = '<span style="background:yellow;">' + word + '</span>';
} else {
word;
}
return word;
}
var str = document.querySelector("#Second").innerText;
var newt = str.trim().split(' ').map(check).join(' ');
document.querySelector("#Second").innerHTML = newt;
}
<div id="Second">Short short thiswordislong short short thiswordislongtoo short</div>

TA贡献1853条经验 获得超6个赞
带有 .|,|? 的版本 检测
const setup = () => {
const p = document.querySelector('p');
wrapWordsWithLengthEight(p);
}
const check = (word) => {
//Check if word include a .|,|?
const hasCharacter = word.includes(".", word.length - 1)
|| word.includes(",", word.length - 1)
|| word.includes('?', word.length - 1);
//Calculate real word length
const wordLength = hasCharacter ? (word.length -1) : word.length;
if(wordLength > 8) {
const spanContent = hasCharacter ? word.substring(0, word.length - 1) : word;
const endCharacter = hasCharacter ? (word.substring(word.length - 1)) : '';
word = `<mark>${spanContent}</mark>${endCharacter} `;
}
else word = `${word} `;
return word;
};
const wrapWordsWithLengthEight = (target) => {
//Render HTML to target
const text = (target.textContent).trim().split(' ').map(check).join('');
target.innerHTML = text;
}
window.addEventListener('load', setup);
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Similique enim quod quos, modi architecto, praesentium tenetur suscipit assumenda, sit neque odit, illum minima voluptates? Dolor non dolore accusamus quam maiores.
</p>
添加回答
举报