javascript - 尝试同时设置多个属性

标签 javascript html setattribute

有没有一种好方法可以使用函数设置多个属性,我已经找到了一个带有属性参数的 Elements 原型(prototype),但是当我调用该方法时,我仍然必须写出其中的所有内容。我不确定如何或是否可以创建临时空元素。

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。

我正在尝试使用上面的原型(prototype)来创建一个新函数,该函数允许我添加属性,而无需插入诸如“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 传递到函数中的元素。

最佳答案

有点难以理解你在问什么,但是..就像下面的片段一样?我不明白的是为什么你要尝试创建一个新元素..

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>

关于javascript - 尝试同时设置多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57191459/

相关文章:

html - 带隐藏子菜单的垂直菜单

JavaScript 将图像加载到数组中并在图像源中显示

javascript - 避免 JavaScript 函数中的重复代码

javascript - React js选择所有不在 react 表中的复选框

javascript - 从解码的音频流中清理内存的正确方法(移动)

javascript - 数组数据解析生成HTML表格

javascript - 包含可执行函数代码的字符串

html - 如何让浏览器在缩小窗口时从 srcset 中选择较小的图片?

magento - 在产品信息->库存选项卡中添加属性

Javascript:setAttribute 有效,getAttribute 失败