简体   繁体   English

如何在数组中动态生成的ul中存储li值?

[英]How to store li values in dynamically generated ul , in an array?

I have a unordered list, which will be generated dynamically . 我有一个无序列表,它将动态生成。 I need to store the items in a list in an array . 我需要将项目存储在数组的列表中。

this is my list: 这是我的清单:

 <div id="xaxizd">
 <ul id="xaxiz"   style="list-style: none;" >
 <li></li>
 </ul>
 </div>

I am trying to retrieve the value using this function. 我正在尝试使用此函数检索值。 (Below mentioned code is in document.ready function is self) (下面提到的代码在document.ready函数是self中)

  var lisX = document.getElementById("xaxizd").getElementsByTagName("li"); 
  alert(lisX[0].id);

But it is not working. 但这是行不通的。 Is there any other way to store list item values ? 还有其他方法可以存储列表项的值吗? please help by finding the mistake or by suggesting any other method . 请通过发现错误或建议其他方法来帮助您。

Thanks in advance 提前致谢

Fiddle 小提琴

No jQuery: 没有jQuery:

var arr = document.getElementById("xaxiz").getElementsByTagName("li");
for (i=0;i<arr.length;i++) {
    alert(arr[i].id);
}

jQuery: jQuery的:

$("#xaxiz li").each(function() {
    alert(this.id); 
});

It would be easier for you to do it the other way around. 相反,您这样做会更容易。 Building up your model (such as this array) from the presentation layer (the list) is backwards from good UI design. 从表示层(列表)构建模型(例如此数组)是从良好的UI设计开始的。 If you start over the other way you'll find it easier. 如果您以其他方式重新开始,则会发现它更容易。 Example: 例:

function refreshUL(sources) {
    var ul = jQuery('#myUL');
    jQuery.each(sources, function(i, source) {
         jQuery('<li/>').attr({ key: source.value})
              .text(source.text).appendTo(ul);
    });
}

But as to your immediate issue, your code won't work because you have no id attribute in those <li/> tags. 但是对于您眼前的问题,由于这些<li/>标记中没有id属性,因此代码无法正常工作。

Your li does not have an ID set, so it is returning an empty string, change your HTML to: 您的li没有设置ID,因此返回的是空字符串,请将HTML更改为:

<div id="xaxizd">
<ul id="xaxiz" style="list-style: none;" >
   <li id="test"></li>
</ul>
</div>

and try again.. 然后再试一次..

I just looked it up in the jQuery documentation. 我只是在jQuery文档中进行了查找。 You can loop through all li elements: 您可以遍历所有li元素:

$( "li" ).each(function( index ) {
console.log( index + ": " + $( this ).attr( "id" );
});

Of course you should also add an "id" tag to the html code ;-) 当然,您还应该在html代码中添加“ id”标签;-)

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

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