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>
添加回答
舉報