用户输入商品后内容消失

Content disappears after user finishes entering groceries

本文关键字:消失 输入 用户      更新时间:2023-09-26

大家新年快乐!我通过学习jquery来庆祝。我在下面的代码中添加了一些jQuery,并设法添加了一些内容,并用它更改了一些css。getgrocery函数工作得很好,正在做它应该做的事情。当用户输入完杂货后,程序(printgrocery)应该打印用户输入的列表。这部分也在工作....然而,当发生这种情况时,程序将删除标题(My grocery list)并删除所有样式。

我做错了什么?

EDITED CODE:删除了完整的代码,并添加了我更改的部分(注释了旧的代码)。

function printGroceries(groceryItems) {
if (groceryItems.length > 1) {
    $('grocery-list').html('<ol class="items" id="list-items">');
    //document.write("<ol>");
    for(x=0; x < groceryItems.length;x++){
    groceryItems;
    $('#list-items').prepend('<li>' + groceryItems[x] + '</li>');
    //document.write("<li>" + groceryItems[x] + '</li>');
    }
    $('#grocery-list').append('</ol>');
    //document.write("</ol>");
} else {
    $('#grocery-list').prepend('<p>Sorry, your list is empty.</p>');
    //document.write('<p>Sorry, your list is empty.</p>');
}
}

问题:小提琴

试试这个

function printGroceries(groceryItems) {
    if (groceryItems.length > 0) {
        $('#grocery-list').html('<ol class="items" id="list-items">');
        //document.write("<ol>");
        for(x=0; x < groceryItems.length;x++){
        groceryItems;
        $('#list-items').prepend('<li>' + groceryItems[x] + '</li>');
        //document.write("<li>" + groceryItems[x] + '</li>');
        }
        $('#grocery-list').append('</ol>');
        //document.write("</ol>");
    } else {
        $('#grocery-list').prepend('<p>Sorry, your list is empty.</p>');
        //document.write('<p>Sorry, your list is empty.</p>');
    }
}

你错过了我在评论中建议的一些东西
1. if条件应检查groceryItems.length > 0
2. $('grocery-list')应该是$('#grocery-list'),您缺少id选择器这里

解决方案:小提琴

既然你在使用jQuery;这是一个利用$.each()的版本。此外,最好构建字符串并只追加一次,而不是一次又一次地追加每一项。

function printGroceries(groceryItems) {
  var listItems = '';
  if (groceryItems.length > 0) {
    $.each(groceryItems, function (i, item) {
      listItems += '<li>' + item + '</li>';
    });
    $('#grocery-list').append('<ol class="items" id="list-items">'+listItems+'</ol>');
  } else {
    $('#grocery-list').prepend('<p>Sorry, your list is empty.</p>');
  }
}