如何阅读JavaScript中的<li>列表

时间:2018-06-06 10:20:21

标签: javascript model-view-controller

美好的一天

我在JavaScript中有一个表单,我在<li>上也有隐藏字段,我希望在阅读列表时包含它们。

我想阅读Test1Test2及其隐藏字段并将其存储在binList[]

这是表格

<ul class="nav nav-tabs" id="tabsList">
<li id="Test1TabId"> <a data-toggle="tab" href="#tblTest1">Test1 </a>
    <input type="hidden" id="Test1" name="Name">
    <input type="hidden" id="Test 1 desc" name="Description">
    <input type="hidden" id="1" name="BinType">
    <input type="hidden" id="Client Bin" name="BinTypeName"></li>
<li id="Test2TabId"> <a data-toggle="tab" href="#tblTest2">Test2 </a>
    <input type="hidden" id="Test2" name="Name">
    <input type="hidden" id="Test 2 desc" name="Description">
    <input type="hidden" id="1" name="BinType">
    <input type="hidden" id="Client Bin" name="BinTypeName"></li>

以下是在<ul> tabsList

中加载列表的JavaScript代码
 var binName = $('#Name').val();
 var binDescription = $('#Description').val();
 var binTypeId = $('#SelectBinType').val();
 var binTypeName = $("#SelectBinType option:selected").text();
 var binList = [];

 var binList = [];
 const listItem = Array.from(document.querySelectorAll('#tabsList>li'));
        for (let i = 0; i < listItem.length; i++) {
            Name: binName;
            Description: binDescription;
            BinTypeId: binTypeId;
            BinTypeName: binTypeName;

            binList.push(listItem[i]);
        }

  var finalObject = ({
                Bins: binList

            });

1 个答案:

答案 0 :(得分:0)

您需要使用$()来选择元素,然后找到元素id或值的子元素。 例如:

$(document).ready(function() {
$("#show").click(function() {
    const listItem = $('#tabsList>li');
    var binList = [];

    listItem.each(function() {
        var el = $(this);
        var lists = {};

        lists.name = el.find("input[name=Name]").attr("id");
        lists.description = el.find("input[name=Description]").attr("id");
        lists.bintype = el.find("input[name=BinType]").attr("id");
        lists.bintypename = el.find("input[name=BinTypeName]").attr("id");

        binList.push(lists);
    });

    var finalObject = ({
        Bins: binList
    });
    $("#result").val(JSON.stringify(binList));
});

$("#tabsList li a").click(function() {
    const listItem = $(this).parent("#tabsList li");
    var binList = [];

    var el = listItem;
    var lists = {};

    lists.name = el.find("input[name=Name]").attr("id");
    lists.description = el.find("input[name=Description]").attr("id");
    lists.bintype = el.find("input[name=BinType]").attr("id");
    lists.bintypename = el.find("input[name=BinTypeName]").attr("id");

    binList.push(lists);

    var finalObject = ({
        Bins: binList
    });
    $("#result").val(JSON.stringify(binList));
});
});

https://jsfiddle.net/xpvt214o/195593/