从OL中移除LI元素
Remove an LI element from OL
我知道下面的代码可以删除<ol>
中的第一个子元素,但如果我想按元素在数组中的顺序指定元素,代码会是什么?例如,我的OL有5个LI元素,我想删除第三个元素[2]。
jQuery("#words li:first-child").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="words">
<li>hi</li>
<li>bye</li>
</ol>
jQuery("#words li:nth-child(2)").remove();//note it starts at 1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="words">
<li>hi</li>
<li>bye</li>
</ol>
您可以使用:nth-child()
描述:选择其父元素的第n个子元素。
您可以使用jQuery:nth-child()
或:eq()
Selector来执行您的工作。
:nth-child()选择器
index:要匹配的每个子项的索引,从1开始,字符串偶数或奇数,或一个等式(例如。:第n个子(偶数),:第n子(4n))
:eq()选择器
index:要匹配的元素的从零开始的索引。
例如
<script type="text/javascript">
function removeChild(index) {
// :nth-child() Selector
// index: The index of each child to match, starting with 1.
$('ol li:nth-child(' + index + ')').remove();
// Using :eq() Selector
// index: Zero-based index of the element to match.
$('ol li:eq(' + index + ')').remove();
}
</script>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=euc-kr">
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function click_remove(int){
$('#words li').eq(int).remove();
var a = $('button').length - 1;
$('button').eq(a).remove();
}
</script>
</head>
<body>
<ol id="words">
<li>hi</li>
<li>bye</li>
</ol>
<button onclick="click_remove(0);">romove 1</button>
<button onclick="click_remove(1);">romove 2</button>
</body>
</html>
您可以使用li:eq(1)
选择器。
相关文章:
- 完全可链接的li元素
- 使用li元素的html内容更改该元素的背景
- 需要在量角器中找到使用ng中继器的li元素的数量
- 根据输入值创建li元素
- 要更改变量的高度li元素
- 为li元素添加标题
- 在不使用sort()的情况下获取HTML LI元素的副本
- 将内容从 JSON 数组附加到 li 元素
- 获取 LI 元素的偏移宽度(或等效项)
- addClass 到当前 li 元素并删除类
- 使用纯JS点击即可从li元素中获取文本和id
- Rails-使用Ajax删除li元素
- 对具有相同类级别的不同li元素进行排序
- 显示/隐藏具有不同类的li元素
- 从ul中删除li元素
- 从OL中移除LI元素
- 删除不起作用的li元素
- 从javascript生成的li a元素触发onclick
- 如何使用json对象作为li元素的id属性或使用javascript锚定标记id
- 添加和删除jquery-li元素