javascript - CSS 不适用于标签,write() 方法包含在一个函数中

标签 javascript html css

假设我编写了一个函数,它在两个不同的 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 颜色没有应用到相关文本

  1. 为什么它不起作用?
  2. 如何实现我想要的?

最佳答案

您应该使用 innerHTML 而不是 write 以避免首先删除整个文档。

关于write()

https://developer.mozilla.org/en-US/docs/Web/API/Document/write

Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.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 the HTML or XML 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/

相关文章:

javascript - 使用 PHP 检查是否支持 onbeforeunload

javascript - 在文本框旁边添加一个按钮

JavaScript 函数默认参数无法正常工作

javascript - 访问 jQuery 中的类属性 - 键值对

javascript - 如何制作自定义下拉菜单

javascript - 使用 React 和 react-slick,我只是很难理解如何使用它

javascript - 如何用ngdocs描述一个提供函数集合的返回对象?

javascript - 类型错误 : Cannot delete property 'Symbol(@xml.js.parent)' of#<Node>

javascript - 使用 JavaScript 附加到 JSON 对象

html - 如何在 html 中使用背景图片而不是 IMG 标签?