【问题标题】:Jquery code optimization (method attr () for two different div)?jquery代码优化(方法attr()为两个不同的div)?
【发布时间】:2016-02-28 23:20:19
【问题描述】:

我是 javascript 和 jquery 的新手,每天我都在学习新东西...... 我正在处理一个文件,我发现自己使用了这段代码:

            $('#mobileuser span').attr({                    
                'class': 'fa fa-user',
                'style':''
            });

            $('#mobilesearch span').attr({                  
                'class': 'fa fa-search',
                'style':''
            });

在我摸索优化的过程中,我尝试了这个解决方案但不起作用:

var fontawesome= {          
    mobileuser: 'fa fa-user',
    mobilesearch: 'fa fa-search'    
}

$('#mobilesearch span, #mobileuser span').attr({                    
                'class': fontawesome[$(this).parent('div').attr('id')],
                'style':''
            });

你能建议我优化这段代码的最佳方法吗?

非常感谢,很抱歉这个问题:)

【问题讨论】:

    标签: javascript jquery performance optimization


    【解决方案1】:

    您可以将函数传递给.attr。为每个匹配选择器的元素调用该函数,并且在函数内,this 是特定元素。它应该返回具有特定属性的对象。

    $('#mobilesearch span, #mobileuser span').attr(function() {
        return {                
            'class': fontawesome[$(this).parent('div').attr('id')],
            'style':''
        };
    });
    

    【讨论】:

    • 我试着让你知道 :)
    • 我建议用.class-selector 替换#id-selector span,这将被添加到将保存图标的元素(在本例中为span 标签)。
    • @Barmar 但您的代码在两个 span 中都添加了“return”?真的吗?
    • 我不明白这个问题。
    • 抱歉对我来说很难,因为我是意大利人......我想在返回“#mobilesearch span”和“#mobileuser span”中添加代码,您的代码没有每个( )例如...所以我问你是否首先为“#mobilesearch span”和“#mobileuser span”运行“返回代码”......
    【解决方案2】:

    试试这个:

    $('#mobilesearch span, #mobileuser span').each(function() {
        $(this).attr({                
            'class': fontawesome[$(this).parent('div').attr('id')],
            'style':''
        });
    });
    

    【讨论】:

    • 你不需要 .each()
    • 也许不需要 .each 但你的代码 @gladsocc 是唯一有效的
    猜你喜欢
    • 1970-01-01
    • 2014-03-16
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多