javascript - jquery的find方法能否找多个div,然后分别添加class
伊谢尔伦
伊谢尔伦 2017-04-11 11:45:43
[JavaScript讨论组]

现在的代码是在这样的

    $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多个p,然后设置html或者添加class,我试了下用逗号隔开不行,求指导~。

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(4)
PHPz

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

$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);
高洛峰
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);
}
高洛峰

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号