简体   繁体   English

使用jquery获取列表元素及其类

[英]Get list elements and its classes using jquery

I used $('#ul li').get() to get all the list elements and stored in an array, each of this list elements have classes... 我使用$('#ul li').get()来获取所有列表元素并存储在一个数组中,每个列表元素都有类...

var i;
var listClass = ('#ul li').get();
for(i=0;i<listClass.length;i++){
    var theClass = listClass[i].attr("class"); //<--what's the proper function/method/code for this?
    var content = listClass[i].innerHTML; //<-- works very well

    //other codes here
}

How may i able to get the classes of each list elements...Thanks! 我怎么能够得到每个列表元素的类...谢谢!

You can use jQuery's own map to do that: 你可以使用jQuery自己的map来做到这一点:

alert($('#ul li').map(function() {
    return this.className;
}).get());

http://jsfiddle.net/MhVU7/ http://jsfiddle.net/MhVU7/

for example. 例如。 You can do anything with the returned array. 您可以对返回的数组执行任何操作。

The reason the way you're doing it isn't working is because you're calling the non-existent method .attr on a native DOM element - it's not an extended jQuery object. 你这样做的方式不起作用的原因是你在本机DOM元素上调用不存在的方法.attr - 它不是扩展的jQuery对象。

var lis = document.getElementById("ul").children;
for (var i = 0, len = lis.length; i < len; i++) {
  var li = lis[i],
      className = li.className,
      value = li.value,
      text = li.textContent;

  // code
}

The get() method returns a native array of DOM elements, not a jQuery object. get()方法返回DOM元素的本机数组,而不是jQuery对象。

You should use jQuery: 你应该使用jQuery:

var lists = $('ul li');

var className = lists.eq(i).attr('class');
var content = lists.eq(i).text();

If you want to loop through all the elements 如果你想循环遍历所有元素

$('ul li').each(function(){
var className = $(this).attr('class');
var content = $(this).text();

});

I have commented the code to better help you understand it. 我已经对代码进行了评论,以便更好地帮助您理解它。

$("#ul li").each(function() { /* you should only be using # selector to identify id's - if it's all ul's you want just put ul. */
    var klass = this.className; /* this refers to the native DOM object, which contains className */
    var textContents = this.innerText || this.textContent; /* the text of the list, does not include html tags */
    var childNodes = this.childNodes; /* the child nodes of the list, each unencased string of text will be converted into a TextNode */
    console.log(klass + ' ' + textContents); /* replace console.log with alert if you do not have a console */
    console.log(childNodes);
});

here is an example of the above. 是上面的一个例子。

Good Luck! 祝好运!

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

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