简体   繁体   English

从OL移除LI元素

[英]Remove an LI element from OL

I know the following code works to remove the first child in an <ol> but what would the code be if I wanted to specify the element by its order in the array? 我知道以下代码可以删除<ol>中的第一个孩子,但是如果我想按数组中的顺序指定元素,那么代码将是什么? eg my OL has 5 LI elements and I want to delete the third one [2]. 例如,我的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> 

You can use :nth-child() 您可以使用:nth-​​child()

Description: Selects all elements that are the nth-child of their parent. 说明:选择作为其父级的第n个子级的所有元素。

You can use jQuery :nth-child() or :eq() Selector for performing your job. 您可以使用jQuery :nth-child():eq()选择器执行工作。

:nth-child() Selector :nth-​​child()选择器

index: The index of each child to match, starting with 1, the string even or odd, or an equation ( eg. :nth-child(even), :nth-child(4n) ) index:要匹配的每个子项的索引,从1开始,字符串为偶数或奇数,或者为等式(例如:nth-​​child(even)、: nth-child(4n))

:eq() Selector :eq()选择器

index: Zero-based index of the element to match. index:要匹配的元素的从零开始的索引。

For example - 例如 -

<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)选择器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM