假设我编写了一个函数,它在两个不同的 HTML 标记内写入一些文本,然后在单击按钮时写入页面。 问题是 CSS 样式没有应用到这些标签...但是当我将相关代码放在函数之外时,它工作正常。
我的JS代码,
let i;
function myFunction() {
for (i=0; i<10; i++){
if (i % 2 == 0) {
write_this = "<green>This</green>"
}
else {
write_this ="<red>That</red>"
}
document.write(write_this)
}
}
CSS 代码
green {
color: green;
}
red {
color: red;
}
HTML
<input type="button" onclick="myFunction()" value="My Button">
点击按钮,希望它能正确完成工作...但是那些 CSS 颜色没有应用到相关文本
- 为什么它不起作用?
- 如何实现我想要的?
最佳答案
您应该使用 innerHTML 而不是 write 以避免首先删除整个文档。
关于write()
https://developer.mozilla.org/en-US/docs/Web/API/Document/write
Note: as
document.write
writes to the document stream, callingdocument.write
on a closed (loaded) document automatically callsdocument.open
, which will clear the document.
关于innerHTML
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
The Element property
innerHTML
gets or sets theHTML
orXML
markup contained within the element.
您可能会尝试做的更像是:
let i;
function myFunction() {
var write_this = "";// prepare your var to update on the loop
for (i = 0; i < 10; i++) {
if (i % 2 == 0) {
write_this = write_this + "<green>This</green>"
} else {
write_this = write_this + "<red>That</red>"
}
// you may use a container
document.getElementById("mybox").innerHTML = write_this;
}
}
green {
color: green;
}
red {
color: red;
}
<input type="button" onclick="myFunction()" value="My Button">
<p id="mybox"></p>
关于javascript - CSS 不适用于标签,write() 方法包含在一个函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58892614/