javascript - 尝试同时设置多个属性
问题描述
有没有一种用函数设置多个属性的好方法,我找到了一个接受属性参数的 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 的元素。
解决方案
有点难以理解你在问什么,但是..它类似于下面的片段?我不明白你为什么要创建一个新元素..
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 - 承诺拒绝 - 超时记录放置
- javascript - 无法从函数访问 opencv.js 属性和方法
- c# - 在wpf c#应用程序windows7中显示双向字符的问题
- java - Java中的Arraylists中的Arraylists中的ArrayLists
- apache - 我无法使用 CGI 访问 kubernetes python-client
- javascript - 在 Zapier 中使用 Javascript 时如何克服新行创建问题
- postgresql - 如何通过自制软件控制 postgresql 的版本
- spring - springboot 中的 mybatis mulidatasource 存在问题“在候选人中发现了不止一个 'primary' bean”
- c# - 如何在 dotnet 中创建用于身份验证的自签名证书?
- javascript - 为什么输入值中设置的值仅为字符串类型?