如何在 js 中使用 SHIFT() 方法



我尝试使用 shift(( 方法删除第一个元素。但它没有奏效。如何使用来更正此功能?

     `// id="delete-first" in HTML
     // the element into the array displayed in HTML 
     // I want to delete the first element
    $("#delete-first").click(function(){ 
        $("#list-student").shift(); // I have issue this line
        // $("list-student").first().remove(); // this code is not working too.
    });`
Please, fix it to help me. 
Sincerely.

由于您没有发布 HTML 代码段,这是基于列表项实际上是 #list-student 元素中的子项的假设。因此,您唯一缺少的是注释中提到的#,并且在使用之前获取子元素.first()

$("#delete-first").click(function(){
    $("#list-student").children().first().remove();
});

如果您实际上拥有所有具有相同 ID 的 #list-student 列表项(这是不可取的(,那么您可以这样做

$("#delete-first").click(function(){
    $("[id=list-student]:first").remove();
});

您正在尝试删除#list-student项的第一次出现 - 只需选择它并使用remove

$("#list-student").remove();

无需选择第一个元素,因为 ID 是唯一的。

最新更新