尝试同时设置多个属性

时间:2019-07-24 21:24:42

标签: javascript html setattribute

是否有一个很好的方法来设置一个函数的多个属性,我为Elements找到了一个带有属性参数的原型,但是当我调用该方法时,我仍然必须写出里面的所有内容。我不确定如何或是否有可能创建一个临时的空元素。

Element.prototype.setAttributes = function (attrs) {
    for (var idx in attrs) {
        if ((idx === 'styles' || idx === 'style') && typeof attrs[idx] === 'object') {
            for (var prop in attrs[idx]){this.style[prop] = attrs[idx][prop];}
        } else if (idx === 'html') {
            this.innerHTML = attrs[idx];
        } else {
            this.setAttribute(idx, attrs[idx]);
        }
    }
};

此方法采用如下所示的输入方式

div.setAttributes({     //// This Works
        'id' :  'my_div',
        'class' : 'my_class'
    });

并返回带有添加的属性的div。

我正在尝试使用上述原型创建一个新函数,该函数使我无需添加'class':'my_class'之类的属性即可添加属性。

我希望能够在下面完成

div.inputSet("my_id","my_class");

以下是我尝试过的方法,我不确定是否可行。我有2天的JavaScript经验。

Element.prototype.inputSet = function(ids, classs, types, placeholders){
        var temp: new Element; ///// How to Create an empty element???
        return temp.setAttributes({
            'id' : `${ids}`,
            'class' : `${classs}`,
            'type'  : `${types}`,
            'placeholder' : `${placeholders}`
        });
    };

我想返回一个带有args属性的元素。

1 个答案:

答案 0 :(得分:1)

有点难以理解您的要求,但是..这类似于以下片段吗?我不明白的是为什么您要尝试创建一个新元素。

Element.prototype.setAttributes = function (attrs) {
    for (var idx in attrs) {
        if ((idx === 'styles' || idx === 'style') && typeof attrs[idx] === 'object') {
            for (var prop in attrs[idx]){this.style[prop] = attrs[idx][prop];}
        } else if (idx === 'html') {
            this.innerHTML = attrs[idx];
        } else {
            this.setAttribute(idx, attrs[idx]);
        }
    }
};

Element.prototype.inputSet = function(ids, classs, types, placeholders){
        // just like your "setAttributes" method... use the This to set the attributes
        return this.setAttributes({
            'id' : `${ids}`,
            'class' : `${classs}`,
            'type'  : `${types}`,
            'placeholder' : `${placeholders}`
        });
    };
document.querySelector('#sample').inputSet('abc', 'for');
.for {
 border:1px solid red;
 width:100px;
 height: 100px;
}
<div id="sample"></div>