从OL中移除LI元素

Remove an LI element from OL

本文关键字:LI 元素 OL      更新时间:2024-06-10

我知道下面的代码可以删除<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)选择器。