首页 > jquery的find方法能否找多个div,然后分别添加class

jquery的find方法能否找多个div,然后分别添加class

现在的代码是在这样的

    $container.children().last().find('.time').html(data[i].pTime);
    $container.children().last().find('.textcon').html(data[i].pText);
    if(data[i].pState !== '健康'){
      $container.children().last().find('.dot').addClass('error-dot');
      $container.children().last().find('.triangle').addClass('error-triangle');
      $container.children().last().find('.textcon').addClass('error-textcon');
    }`

有没有更加简便的写法啊?
同时find多个div,然后设置html或者添加class,我试了下用逗号隔开不行,求指导~。


不知道你是怎么用逗号隔开的。

$container.children().last()
    // 可能你是这样写的
    .find('.dot','.triangle')
    // 应该这样写
    .find('.dot,.triangle')
    .each(function(v){
        // 然后在each里面去写你的逻辑
    });
    
    

然后给你个建议。

$container.children().last().find('.time').html(data[i].pTime);

这里 $container.children().last() 重复写了很多次,这样是很消耗性能,你应该用变量先缓存下来。
然后后续只需引用该变量即可,这样写的代码都少了。

var $last = $container.children().last();
$last.find('.time').html(data[i].pTime);
$last.find('.textcon').html(data[i].pText);

你为什么不在这几个上面添加同一个class


var $target = $container.children().last();
$target.find('.dot, .triangle, .textcon').each(function (i, n) {
    var $this = $(n);
    switch(n.className) {
        case 'dot':
            $this.addClass('error-dot');
            break;
        case 'triangle':
            $this.addClass('error-triangle');
            break;
        case 'textcon':
            $this.addClass('error-textcon');
            break;
    }
});

不会装个简单的函数吗?

function xxx($container.children().last(),textcon,error-textcon){
      p.find(textcon).addClass(error-textcon);
}
【热门文章】
【热门文章】