可以使用$()来创建DOM节点。例如$("<div>hello foxdevelop.com</div>")会生成一个jQuery节点对象,可以调用jQuery各类方法操作。
注意:创建出来的元素还没有添加到页面时,无法用选择器找到。
节点添加方法:
append():在元素结束标签前追加,添加子节点prepend():在元素开始标签后添加,添加子节点after():在目标元素后面添加,添加同级兄弟节点before():在目标元素前面添加,添加同级兄弟节点
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm21.aspx.cs" Inherits="WebApplication1.WebForm21" %>
<!DOCTYPE html>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
<script type="text/javascript">
$(function () {
//页面加载完成时执行
var div = $("<div>hello bamn.cn</div>");
div.attr("style", "color:red");
$('body').html(div);
var p = $("<p></p>");
p.text("foxdevelop");
//追加到div内部 <div><p></p></div>
$('div:first').append(p);
//和div同级,放在前面 <p></p><div></div>
//$('div:first').before(p);
//和div同级,放在后面 <div></div><p></p>
//$('div:first').after(p);
});
</script>
</head>
<body>
</body>
</html>
Code language: HTML, XML (xml)
说明:
$("<div>hello bamn.cn</div>")创建div元素,设置文字颜色红色html(div)把body里面内容替换成这个div- 创建p标签,使用
append追加到div内部作为子元素
Previous: 遍历元素 each函数
Next: 练习-实现一个异步评论和加载列表