操作jquery集合

Manipulating a jquery collection

本文关键字:集合 jquery 操作      更新时间:2023-09-26

我有一个JQuery集合创建:

var children = $('span[data-Parent="7"]');

现在我想操作该集合中项目的css类。我试过:

for (var i = 0; i < children.length; i++) {
    var $child = children[i];
    if ($child.hasClass("red")) {
        $child.addClass("green");           
    }

但是得到错误,指出对象没有方法hasClass。如何使集合的元素成为文档元素,以便对其进行操作?

必须将DOM元素包装为jQuery对象。使用jQuery迭代元素通常通过提供的每个函数来完成:

$('span[data-Parent="7"]').each(function(){
   if ($(this).hasClass('red')) {
      $(this).addClass('green');
   }
});

注意整个代码可以简化为

$('span[data-Parent="7"].red').addClass('green');

我建议使用$.each:

$.each(children, function(i, child) {
    if ($(child).hasClass("red")) {
        $(child).addClass("green");
    }
});

只需循环遍历每个子节点并在.each循环中运行检查。

var children = $('span[data-Parent="7"]');
children.each(function(index)
{
    var self = $(this);
    if (self.hasClass("red"))
    {
        self.addClass("green");
    }
});

修改代码为:

var $child = $(children[i]);
//the rest of the code