如何将列表项分组以提高可读性

how to Group my list items for more readability

本文关键字:可读性 列表      更新时间:2024-07-05

我的列表结果显示我需要在显示的列表结果之间创建空间或将它们分组我尝试使用break标签,但它们不起作用

function GetProductDetails(barcodeId, coords)
{
    $.getJSON("api/products/?barcodeId=" + barcodeId + "&latitude=" + coords.latitude + "&longitude=" + coords.longitude)
        .done(function (data)
        {
            $('#result').append(data.message)
            console.log(data)
            var list = $("#result").append('<ul></ul>').find('ul');
            $.each(data.results, function (i, item)
            {
                if(data.results == null)
                {
                    $('#result').append(data.message)
                }
                else
                {
                    list.append('<li>ShopName :' + item.retailerName + '</li>');
                    list.append('<li>Name : ' + item.productName + '</li>');
                    list.append('<li>Rand :' + item.price + '</li>');
                    list.append('<li>Distance in Km :' + item.Distance + '</li>');
                }
            });
            $("#result").append(ul);
        });
}
list.append('<li><b>ShopName</b><p>' + item.retailerName + '</p></li>');
list.append('<li><b>Name</b><p>' + item.productName + '</p></li>');
list.append('<li><b>Rand</b><p>' + item.price + '</p></li>');
list.append('<li><b>Distance</b><p>' + item.Distance + '</p></li>');

非常确定list始终是结果框中的第一个ul,无论实际添加了多少。此外,您的最终$("#result").append(ul)是一个错误,因为没有ul变量。

试试这个:

var list = document.getElementById('result').appendChild(document.createElement('ul'));
data.results.forEach(function(item) {
    list.appendChild(document.createElement('li'))
              .appendChild(document.createTextNode("ShopName : "+item.retailerName));
    list.appendChild(document.createElement('li'))
              .appendChild(document.createTextNode("Name : "+item.productName));
    list.appendChild(document.createElement('li'))
              .appendChild(document.createTextNode("Rand : "+item.price));
    list.appendChild(document.createElement('li'))
              .appendChild(document.createTextNode("Distance in Km : "+item.Distance));
});

VanillaJS可能写起来更冗长,但一旦你克服了这个心理障碍,它就更容易理解和使用;)当然,没有什么可以阻止你创建一个助手函数:

function addLIwithText(ul,text) {
    ul.appendChild(document.createElement('li'))
                       .appendChild(document.createTextNode(text));
}

然后你的循环内容变成:

addLIwithText(list,"ShopName : "+item.retailerName);
// and so on