JQuery对列表的增删改以及遍历
Elora Rinta!

问题描述

使用JQuery对html中的ul进行li的增删改以及遍历查看

代码

html部分

1
2
3
4
5
6
7
8
9
10
11
12
<div>
<ul>
</ul>
</div>
<button id="addItem">添加元素</button>
<button id="deleteItem">删除元素</button>
<button id="traversal">显示列表</button>
<input type="text" placeholder="输入修改第几项" id="index">
<input type="text" placeholder="修改的值" id="value">
<button id="modifyItem">改变列表项</button>
<br>遍历结果:
<p id="res"></p>

script部分

list增加元素:

1
2
3
4
5
6
$("#addItem").click(function() {
let newItem = "";
newItem = "<li>" + i + "</li>";
i += 1;
$("ul").append(newItem);
});

list删除元素:

1
2
3
4
5
6
$("#deleteItem").click(function() {
let tmp = $("ul").html().toString();
let location = tmp.lastIndexOf('<li>');
$('ul').html(tmp.slice(0, location));
i -= 1;
});

list修改特定项的元素:

1
2
3
4
5
$("#modifyItem").click(function() {
let index = $("#index").val();
let value = $("#value").val();
$("li").eq(index - 1).text(value);
});

list遍历:

1
2
3
4
5
6
7
$("#traversal").click(function() {
let res = [];
for (j = 0; j < $("li").length; j++) {
res.push($("li").eq(j).text())
}
$("#res").text(res);
});

全部代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
let n = 6,
i = 1;
let text = "";
for (i; i < n; i++) {
text += "<li>" + i + "</li>";
}
$("ul").append(text);
$("#addItem").click(function() {
let newItem = "";
newItem = "<li>" + i + "</li>";
i += 1;
$("ul").append(newItem);
});
$("#deleteItem").click(function() {
let tmp = $("ul").html().toString();
let location = tmp.lastIndexOf('<li>');
$('ul').html(tmp.slice(0, location));
i -= 1;
});
$("#traversal").click(function() {
let res = [];
for (j = 0; j < $("li").length; j++) {
res.push($("li").eq(j).text())
}
$("#res").text(res);
});
$("#modifyItem").click(function() {
let index = $("#index").val();
let value = $("#value").val();
$("li").eq(index - 1).text(value);
})
})
</script>
</head>

<body>
<p>July 16th</p>
<div>
<ul>
</ul>
</div>
<button id="addItem">添加元素</button>
<button id="deleteItem">删除元素</button>
<button id="traversal">显示列表</button>
<input type="text" placeholder="输入修改第几项" id="index">
<input type="text" placeholder="修改的值" id="value">
<button id="modifyItem">改变列表项</button>
<br>遍历结果:
<p id="res"></p>
</body>
</html>
 Comments
Comment plugin failed to load
Loading comment plugin
Powered by Hexo & Theme Keep
This site is deployed on
Total words 75.1k Unique Visitor Page View