The following function creates input fields where the user specifies type, name and a number of classes that he would like to add for the input element. Sometimes, the user is going to want to set other attributes for the element, such as step
, or any other DOM attribute. That's why I want to use optional arguments:
function createInputField(type, name, classList, optional){
var input = document.createElement('input');
input.type = type;
input.name = name;
for(var i=0; i<classList.length; i++){
input.classList.add(classList[i]);
}
for(key,value) in optional{ // Ugly fake code. How do I implement this in Javascript?
input.getAttribute(key) = value;
}
return input;
}
input = createInputField("number", "numberfield", ["red", "top"], {"step":"0.05"})
How do I implement this functionality in Javascript?
答案 0 :(得分:1)
只需使用普通对象枚举:
for (var key in optional) {
var value = optional[key];
input.setAttribute(key, value);
}
这不必对参数optional
本身是可选的做任何事情,以便您可以在调用中省略它。当您不想传递任何额外的dom属性时,只需提供一个空对象({}
)。
如果你想完全省略它(比如调用createInputField("number", "x", ["red"])
,你可以将循环包裹在if (typeof optional == "object")
条件中,或者使用default parameters:
function createInputField(type, name, classList = [], optional = {}) {
…
}
答案 1 :(得分:1)
这就是你需要的:
if(optional && typeof optional === 'object') {
for(var key in optional) {
if(input.hasOwnProperty(key)) {
input.getAttribute(key) = optional[key];
}
}
}