此脚本的目标是删除文本块的第一个字母-firstLetter
-并将其替换为newFirstLetter
。
const initialLetter = (firstParagraph) => {
let firstLetter = firstParagraph.innerHTML.charAt(0)
let newFirstLetter = "<span class='initial-letter'>" + firstLetter + "</span>"
let paragraphContent = firstParagraph.innerHTML
// this is not working
paragraphContent.substr(0, 1)
// this is working
firstParagraph.insertAdjacentHTML('afterbegin', newFirstLetter)
}
到目前为止,此行firstParagraph.insertAdjacentHTML('afterbegin', newFirstLetter)
可以正常工作,但是此行paragraphContent.substr(0, 1)
并未删除该内容块中的第一个字母。我想知道我在做什么错了吗?
此脚本的当前输出为:
<p><span class="initial-letter">E</span>Every day we see the potential technology provides to create better pathways of care—for the people delivering care and the patients they treat who are managing their own chronic disease(s). Rock Health reported that since 2011, $23B has been invested in thousands of digital health companies. Yet, historically, innovative solutions for kidney disease have been static at best and from a funding perspective, largely very quiet.</p>
答案 0 :(得分:2)
javascript中的字符串是不可变的,因此您不能仅对其进行更改,您需要将更改后的版本重新分配给innerHTML
let p = document.getElementById('p')
const initialLetter = (firstParagraph) => {
let firstLetter = firstParagraph.innerHTML.charAt(0)
let newFirstLetter = "<span class='initial-letter'>" + firstLetter + "</span>"
let paragraphContent = firstParagraph.innerHTML
firstParagraph.innerHTML = paragraphContent.substr(1)
// this is working
firstParagraph.insertAdjacentHTML('afterbegin', newFirstLetter)
}
initialLetter(p)
span.initial-letter {
color:red
}
<p id='p'>Every day we see the potential technology provides to create better pathways of care—for the people delivering care and the patients they treat who are managing their own chronic disease(s). Rock Health reported that since 2011, $23B has been invested
in thousands of digital health companies. Yet, historically, innovative solutions for kidney disease have been static at best and from a funding perspective, largely very quiet.</p>
答案 1 :(得分:0)
您可以将第一个字母切成薄片,然后在其上附加新内容
var field = document.getElementById("test").innerHTML;
var edited = document.getElementById("edited");
var newField = field.slice(1);
edited.innerHTML = "This is after slice: " + newField;
console.log(newField);
<div id="test">Hello</div>
<div id="edited"></div>