gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:54:24 27 4
gpt4 key购买 nike

有没有用一个函数设置多个属性的好方法,我找到了一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com