【问题标题】:What is the correct approach to adding classes to an array of DOM objects using jQuery?使用 jQuery 将类添加到 DOM 对象数组的正确方法是什么?
【发布时间】:2016-07-24 10:34:54
【问题描述】:

我尝试了两种迭代技术,但都产生了相同的错误:

addClass 不是函数

第一个使用for的例子:

function game(){
    var cards = $('.card');

    function initialize(){
        for(var x = 0; x < cards.length; x++) {    
            cards[x].addClass('wtf');    
        }
    };
};

第二次尝试使用每个:

function game(){
    var cards = $('.card');

    function initialize(){
        //Add random key values to pairs of cards
        $.each( cards ,function(i, ele) {    
            ele[i].addClass('wtf');
        });
    };
};

操作这些类型的数组的正确方法是什么?

【问题讨论】:

  • $('.card').addClass('wtf'); jQuery 会为您遍历每一个,您不必这样做。我错过了什么吗?

标签: jquery html css arrays dom


【解决方案1】:

您的代码示例不起作用,因为您尝试在 DOMElement 而不是 jQuery 对象上调用 jQuery 方法 addClass

如果多个元素与 jQuery 对象中的选择器匹配,addClass() 方法将在内部为您执行循环,因此您只需进行一行调用:

function game(){
    var $cards = $('.card');

    function initialize() {
        $cards.addClass('wtf');
    };
};

例如,我如何能够选择第 5 张卡片并仅将课程添加到该卡片?

为此,您可以使用eq() 方法:

$cards.eq(4).addClass('wtf');

请注意,索引是从零开始的,因此第 5 个元素是索引 4。

【讨论】:

  • 谢谢!上面的示例将 'wtf' 类添加到数组中的所有 DOMElements。但是,例如,我如何能够选择第五张卡片并将类添加到该卡片?
  • 您可以使用eq() 方法来做到这一点:$cards.eq(4).addClass('wtf'); 我为您更新了答案。
【解决方案2】:

cards[x] 是一个 DOM 元素,使用 $(cards[x]) jQuery 对象,如下所示。

function game() {
    var cards = $('.card');

    function initialize() {
        for (var x = 0; x < cards.length; x++) {
            //change following line. 
            $(cards[x]).addClass('wtf');
        }
    };
};

您不需要遍历所有元素。你不能像下面这样只使用cards .addClass('wtf')

function game() {
    var cards = $('.card');

    function initialize() { 
        cards.addClass('wtf');
    };
};

如果您想选择特定卡,请使用 eq() 方法,如下所示。

cards.eq(4).addClass('wtf');   //eq(4) will select 5th card

【讨论】:

  • 感谢 Azim,看来我可以使用 for 循环来选择特定卡片。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-31
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 2010-10-03
相关资源
最近更新 更多