Maf*_*ffe 2 javascript css xhtml css-selectors html-lists
我有以下清单:
<ul id="objects-list">
<li>Table</li>
<li>Chair</li>
<li>Window</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
使用以下 CSS(取自https://www.w3schools.com/howto/howto_css_bullet_color.asp):
ul {
list-style: none;
}
ul li::before {
content: "\2022";
color: red;
font-weight: bold;
display: inline-block;
width: 1em;
}
Run Code Online (Sandbox Code Playgroud)
这会将默认列表标记更改为红色。一切正常,但是当我使用 Javascript 将新项目添加到列表中时
var objectsList = document.getElementById("objects-list");
var listItem = document.createElement("LI");
listItem.innerHTML = "Pen";
objectsList.appendChild(listItem );
Run Code Online (Sandbox Code Playgroud)
它发生在我的 XHTML 文件中。它不会发生在 Stack Snippet 中。
该项目已正确添加到列表中,但根本没有标记。此外,当我在 Inspector 中检查新项目时,它根本没有显示“::before”元素。
有人可以解释我为什么吗?
我已设法使用XHTML文件复制了您的问题。
问题是 XHTML区分大小写,li
!= LI
。更改添加要使用的元素的代码li
:
var listItem = document.createElement("li");
// ????????????????????????????????????^^
Run Code Online (Sandbox Code Playgroud)
这是一个完整的 XHTML 文件,演示了该问题。如果您想在本地验证它,请确保提供正确的文件Content-Type
(使用扩展名.xhtml
并从文件系统打开它也可以,至少在 Chrome 及其变体中):
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>XHTML CSS Problem</title>
<style>
ul {
list-style: none;
}
ul li::before {
content: "\2022";
color: red;
font-weight: bold;
display: inline-block;
width: 1em;
}
</style>
</head>
<body>
<ul id="objects-list">
<li>Table</li>
<li>Chair</li>
<li>Window</li>
</ul>
<script>
var objectsList = document.getElementById("objects-list");
var listItem = document.createElement("LI");
listItem.innerHTML = "Pen";
objectsList.appendChild(listItem );
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)