简体   繁体   English

如何使用方法应用一组 css 属性,而无需链接/jquery

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

I'm currently running the following code to apply an array of css attributes to mimic jquery (I'm not allowed to use jquery) but the loop is only grabbing the first node:我目前正在运行以下代码来应用一组 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'
});

What is wrong with my loop?我的循环有什么问题?

The function is exited as soon as the first loop executes due to the return statement.由于return语句,函数在第一个循环执行后立即退出。 Move the return outside of the loop: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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM