[英]Can you set multiple attributes with the DOM's setAttribute function?
假設我想使用 DOM 創建一個輸入元素。 而不是做這樣的事情
var input = document.createElement("input");
input.setAttribute("class", "my-class");
input.setAttribute("type", "checkbox");
input.setAttribute("checked", "checked");
有沒有一種 DRYer 方法可以將這三行代碼寫成一行。
我知道你可以做這樣的事情
var attributes = ["class", "type", "checked"];
var values = ["my-class", "checkbox", "checked"];
for (var i = 0; i < attributes.length; i++) {
input.setAttribute(attributes[i], values[i])
end
問題是,只有當您有大量需要添加的屬性時,這才有用。 如果你只有兩三個,這就更不DRY了。
無論如何我可以干掉這段代碼嗎?
我個人認為你把DRY走得太遠了(這三個語句做了不同的事情,所以我看不出它怎么不是 DRY。)但是如果你必須抽象它,只需編寫一個函數來完成它:
var input = document.createElement("input"); function setAttributes(el, options) { Object.keys(options).forEach(function(attr) { el.setAttribute(attr, options[attr]); }) } setAttributes(input, {"class": "my-class", "type": "checkbox", "checked": "checked"}); console.log(input);
在 jQuery 中,您可以執行以下操作:
var $input = $("<input>", {class: "my-class", type: "checkbox", checked:"checked"});
是的,您可以使用 Jquery。
$(input).attr(
{
"data-test-1": num1,
"data-test-2": num2
});
Element.setAttribute
設置單個屬性,但您可以輕松編寫一個輔助函數:
function setAttributes(elements, attributes) {
Object.keys(attributes).forEach(function(name) {
element.setAttribute(name, attributes[name]);
})
}
用法:
var input = document.createElement("input");
setAttributes(input, {
class: "my-class",
type: "checkbox",
checked: "checked"
})
正如其他答案所說,您也可以使用$.attr
。 如果您的項目已經使用 jQuery,那就太好了。 如果沒有,我會使用這個函數,而不是為一個簡單的任務添加一個相當重量級的依賴項。
var opt = {"class":"my-class", "type": "checkbox", "checked":"checked"};
Object.keys(opt).forEach( function(key){ input.setAttribute(key,opt[key]); } );
沒有框架或庫(甚至輔助函數)的優雅方法是使用:
Object.assign(element, attributes);
其中第二個參數attributes
是一個對象字面量,其中:
keys
代表屬性屬性values
表示屬性值。這意味着:
var input = document.createElement("input");
input.setAttribute("class", "my-class");
input.setAttribute("type", "checkbox");
input.setAttribute("checked", "checked");
可以寫成:
const input = document.createElement("input");
Object.assign(input, {class: 'my-class', type: 'checkbox', checked: 'checked'});
或者,如果您願意:
const input = document.createElement("input");
Object.assign(input, {
class: 'my-class',
type: 'checkbox',
checked: 'checked'
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.