以下代码从 div 创建 li,但 div 仍然出现在源代码中,我错过了什么?:
$(document).ready(function(){
var makeLI = $("div").html("<li class='blue'>" +
"Here is a new <li > element.</li>");
$("body").append("<ul>");
$("ul").append(makeLI);
});
一份出版物指出:
Navigate to the file in your browser. The elements are converted to elements with the text we want displayed.
但是在 FF 6 中 div 仍然存在:
<div><li class="blue">Here is a new <li > element.</li></div>
------------------完整代码------------------
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
.blue { color:blue; }
</style>
</head>
<body>
<h1>Rewriting three <div> elements</h1>
<div></div>
<div></div>
<div></div>
</body>
</html>
$(document).ready(function(){
var makeLI = $("div").html("<li class='blue'>" +
"Here is a new <li > element.</li>");
$("body").append("<ul>");
$("ul").append(makeLI);
});
最佳答案
makeLI
是 div
元素。 li
是它的子元素。当然,如果您将 div
附加到某处,它就会在那里。如果您只想附加 li
元素,则必须调用 children
:
$("ul").append(makeLI.children());
或者直接省略 div
:
$('body').append($("<ul />").append("<li class='blue'>" +
"Here is a new <li > element.</li>"));
顺便说一句。 div
将出现在所有浏览器中。您可能看不到它,因为浏览器倾向于纠正无效的 HTML。 ul
元素内的 div
元素无效,它可能会被移动到 ul
之后。尽管如此,您应该创建有效 HTML。
关于jQuery .html() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7140317/