系列课程目录
第十八讲 jQuery操作DOM
前言
jQuery操作DOM
提示:以下是本篇文章正文内容,下面案例可供参考
一、jQuery操作DOM
1.jQuery添加节点
使用jQuery工厂函数
(
)
可
以
创
建
H
T
M
L
元
素
∗
∗
()可以创建HTML元素 **
()可以创建HTML元素∗∗(HTML标签)**
添加节点
append()
可以直接传入HTML代码
可以添加多个元素
原代码:
所列方法的返回值均为原jQuery对象
如
(
"
u
l
"
)
.
a
p
p
e
n
d
(
"
<
l
i
>
n
e
w
<
/
l
i
>
"
)
的
返
回
值
为
("ul").append("<li>new</li>") 的返回值为
("ul").append("<li>new</li>")的返回值为(“ul”)
以上所列方法与前面所列方法执行的任务相同。不同之处在于内容的位置和选择器。
所列方法的返回值均为原jQuery对象
练习:使用jQuery对按钮绑定事件,当点击该按钮时,在文本开头处添加“^”符号,结尾处添加“< em >$< /em >”符号
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>Hello world</h1>
<input type="button" name="" id="" value="添加符号" onclick="tj()"/>
<script type="text/javascript" src="js/new_file.js">
</script>
<script type="text/javascript">
function tj(){
$("<em>^</em>").prependTo("h1")
$("<em>$</em>").appendTo("h1")
}
</script>
</body>
</html>
2.jQuery删除节点
remove()
删除被选元素及其子元素
可输入参数进行过滤
empty()
删除被选元素的所有子元素
原代码:
3.jQuery获取节点
原代码:
**练习:使用jQuery对右侧按钮(不能修改HTML代码)绑定事件,点击按钮时,删除对应的输入框及按钮本身
**
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="js/new_file.js">
</script>
</head>
<body>
<input type="text" name="" id="item-1" value="" /><input type="button" name="" id="" value="删除1" />
<input type="text" name="" id="item-2" value="" /><input type="button" name="" id="" value="删除2" />
<input type="text" name="" id="item-3" value="" /><input type="button" name="" id="" value="删除3" />
<script type="text/javascript">
var $btn=$("input[type='button']");
console.log($btn);
$btn.click(sc);
function sc(){
$(this).prev().remove();
$(this).remove();
}
</script>
</body>
</html>
二、课堂作业
1.按照要求完成任务
如下(示例):
2.解析代码
- 任务18-1
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="js/new_file.js">
</script>
</head>
<body>
<script type="text/javascript">
$('body').append("<input type='text'/>")
$("input").keydown(function(event) {
if (event.keyCode == 13) {
add();
}
});
function add() {
var nr="<li>"+$('input').val()+"<input type='button' name='' id='' value='↑' οnclick='up()'/><input type='button' name='' id='' value='↓' οnclick='down()'/><input type='button' name='' id='' value='删除' οnclick='del()'/></li>"
$("input[type='text']").after(nr)
}
function up(){
$f=$(event.target).parent();
$f.prev().before($f)
}
function down(){
$f=$(event.target).parent();
$f.next().after($f)
}
function del(){
$f=$(event.target).parent();
$f.remove();
}
</script>
</body>
</html>