从 UL 中删除选定的 LI

Removing the selected LI from a UL

本文关键字:LI 删除 UL      更新时间:2023-09-26

我正在尝试删除类已"选择"的选定项目,但不仅仅是删除 LI 项目,而是清除了整个列表。我正在使用jQuery。

我整理了一个快速的小提琴:

http://jsfiddle.net/6QvvC/4/

<!DOCTYPE html>
<html>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="jquery.min.js"></script> 
<head>
<style type="text/css">
* {
    font-size: 9pt;
    font-family: Segoe UI;
}
#refdocs {
    border: 0;
    padding: 2px;
}
#box1 {
    border: 1px solid rgb(170,170,170);
    width: 200px;
}
#box2 {
    width: 100%;
    display: block;
    position: relative;
    border-bottom: 1px solid rgb(170,170,170);
}
#container {
    height: 100px;
    overflow-y: scroll;
    overflow-x: hidden;
}
#list1 {
    width: 100%;
}
#list1 ul {
    margin: 0;
    padding: 0px;
    list-style-type: none;
}
#list1 li {
    cursor: default;
    padding: 2px;
}
.selected {
    background: rgb(228,228,228);
}
</style>
<script type="text/javascript">
window.onload = function() {
refresh_list()
}
function remove_selected_item() {
    if ( $('#list1 ul li').hasClass("selected") ) {
        alert("yup")
        $('#list1 ul li').remove()  
    }
    else {
        alert("nope")
    }
}

function refresh_list() {
    $('#list1 ul li').click(function () {
        $('#list1 ul li').removeClass('selected');
        $(this).addClass('selected');
        document.getElementById('refdocs').value = $(this).text()
    });
}
</script>
</head>
<body>
<div id="box1">
<div id="box2"><input type="text" id="refdocs"></div>
<div id="container">
    <div id="list1">
        <ul>
          <li>Coffee</li>
          <li>Tea</li>
          <li>Milk</li>
        </ul>
    </div>
</div>
</div>
<input type="button" value="delete" onclick="remove_selected_item()">
</body>
</html>

函数可以简化:

function remove_selected_item() {
    $('#list1 ul li.selected').remove()
}

您需要删除选定的项目 - 因此您选择具有类.selectedli并将其删除。

演示:http://jsfiddle.net/6QvvC/3/

jQuery选择器#list1 ul li匹配ul内的所有li元素,ID为list1。 如果任何匹配的元素包含给定的类,则hasClass返回 true。 remove删除所有匹配的元素,在给定的情况下,这些元素是所有列表元素。这就是清除列表的原因。

也许可以深入了解一下jQuery选择器的强大功能:http://codylindley.com/jqueryselectors/您不仅可以根据元素的类型或 ID 选择元素,还可以根据它们的类、属性、它们在 DOM 中的位置(父母、兄弟姐妹、孩子)和状态(例如悬停)来选择元素。

在列表元素上安装单击处理程序时,事件委派模式也非常有用: https://learn.jquery.com/events/event-delegation/它可以帮助您更好地了解事件和处理程序安装如何与 jQuery 配合使用。这至少对我来说是某种启示。