如何在不链接/jquery的情况下使用方法应用css属性数组

How to apply an array of css attributes with a method, without chaining/jquery

本文关键字:使用方法 情况下 应用 css 数组 属性 jquery 链接      更新时间:2023-09-26

我目前正在运行以下代码,以应用一组css属性来模拟jquery(不允许我使用jquery),但循环只获取第一个节点:

HTMLElement.prototype.css = function(attr) {
    for(i in attr){
        return this.style[i] = attr[i];
    }
}
button.css({
    'width': '58px',
    'height': '55px',
    'font-family': 'century gothic',
    'font-weight': 'bold',
    'padding-left': '2px',
    'padding-top': '0',
    'outline': 'none'
});

我的循环出了什么问题?

由于return语句,一旦执行第一个循环,函数就会退出。将return移出循环:

HTMLElement.prototype.css = function(attr) {
    for (i in attr) {
        this.style[i] = attr[i];
    }
    return this; // return the original element to enable chaining
}
var button = document.getElementById('foo');
button.css({
    'width': '58px',
    'height': '55px',
    'font-family': 'century gothic',
    'font-weight': 'bold',
    'padding-left': '2px',
    'padding-top': '0',
    'outline': 'none'
});
<button id="foo">Foo</button>

相关文章: