如何在每次输入后重置列表

How do I reset the list after each input?

本文关键字:列表 输入      更新时间:2023-09-26

这是乒乓球测试。每次我单击"开始"按钮并输入一个数字,它就会添加到列表中。如何在每次输入后重置列表?

$(document).ready(function() {
    $("#Start").click(function() {
        var number = parseInt(prompt("Please pick an integer to play."));
        for(index = 1; index <= number; index +=1) {
            if (index % 15 === 0) {
                $('#list').append("<li>" + "ping-pong" + "</li>");
            } else if (index % 3 === 0) {
                $("#list").append("<li>" + "ping" + "</li>");
            } else if (index % 5 === 0 ) {
                $("#list").append("<li>" + "pong" + "</li>");
            } else {
                $("#list").append("<li>" + index + "</li>");
            }
        }
    });
});

要重置(清空)您的列表,请使用

$('#list').empty();

提示之前,从#list 中删除li元素

$("#Start").click(function() {
    $("#list li").remove();
    var number = parseInt(prompt("Please pick an integer to play."));

不执行.append,而是执行.html()

.append添加了一个新的子元素,但.html()清除了它的所有子元素,并使您添加的新元素成为它的子元素。

试用:

$(document).ready(function() {
    $("#Start").click(function() {
        var number = parseInt(prompt("Please pick an integer to play."));
        for(index = 1; index <= number; index +=1) {
            if (index % 15 === 0) {
                $('#list').html("<li>" + "ping-pong" + "</li>");
            } else if (index % 3 === 0) {
                $("#list").html("<li>" + "ping" + "</li>");
            } else if (index % 5 === 0 ) {
                $("#list").html("<li>" + "pong" + "</li>");
            } else {
                $("#list").html("<li>" + index + "</li>");
            }
        }
    });
});