简体   繁体   English

如何在循环中从listitem /无序列表的输入中获取值

[英]How to get value from a input from listitem / unordered list in a loop

I am trying to create a general JS to get the id and value from the input. 我正在尝试创建一个通用的JS,以从输入中获取ID和值。 Then, put those into a JsonObject to pass back to the server. 然后,将它们放入JsonObject中以传递回服务器。 The list is like this: 清单是这样的:

<ul id="myList" data-role="listview" data-inset="true">
    <li> Field One <input id="Field_One" /></li>
    <li> Field Two <input id="Field_Two" /></li>
    <li> Field Three <input id="Field_Three" /></li>
    <li> Field Four <input id="Field_Four" /></li>
</ul>

I could get the data for the listitem, 我可以获取列表项的数据,

function Test(){
    var unorderedList = document.getElementById('myList'); 
    var ListItems = unorderedList.getElementsByTagName('li');  
    var listID

    for (var i = 0; i < ListItems.length; i++) {
        listID = ListItems[i].firstChild.data;
        //alert(listID);
    };  
}

but I couldn't go further to get the text ID or value. 但我无法进一步获取文本ID或值。 (well, if i have id then i can get value...). (好吧,如果我有身份证,那么我可以得到价值...)。

How do I get the input id/value in the ul/il with a loop? 如何通过循环获取ul / il中的输入id /值?

No one is saying the firstChild will be the input. 没有人说firstChild将作为输入。 In fact, it's most probably a text node. 实际上,它很可能是文本节点。

Give it a try: 试试看:

function Test() {
    var unorderedList   = document.getElementById('myList'),
        ListItems       = unorderedList.getElementsByTagName('li');  

    for (var input, i = 0; i < ListItems.length; i++) {
        input = ListItems[i].getElementsByTagName('input')[0];
        console.log(input.id, input.value);
    }
}

Code Example 代码示例

You could use getAttribute to fetch the id. 您可以使用getAttribute来获取ID。 So: 所以:

 listID = ListItems[i].firstChild.getAttribute('id');

You could just directly get the inputs. 您可以直接获取输入。 In your example there does not appear to be a reason to get the LIs first: 在您的示例中,似乎没有理由先获得LI:

http://jsfiddle.net/ysL5B/ http://jsfiddle.net/ysL5B/

function Test(){
    var unorderedList = document.getElementById('myList'); 
    var ListItems = unorderedList.getElementsByTagName('input');  

    for (var i = 0; i < ListItems.length; i++) {
        console.log(ListItems[i].id);
        console.log(ListItems[i].value);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM