您可以使用DOM的setAttribute函数设置多个属性吗? [英] Can you set multiple attributes with the DOM's setAttribute function?
本文介绍了您可以使用DOM的setAttribute函数设置多个属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我想使用DOM创建输入元素.而不是像这样
Let's say I wanted to create an input element using the DOM. Instead of doing something like this
var input = document.createElement("input");
input.setAttribute("class", "my-class");
input.setAttribute("type", "checkbox");
input.setAttribute("checked", "checked");
是否存在将这三行代码写成一行的DRYer方法.
Is there a DRYer way to write these three lines of code into one line.
我知道你可以做这样的事情
I know you could do something like this
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更少.
The problem is that is only helpful if you have a boatload of attributes you need to add. If you only have two or three, this is even less DRY.
反正我可以结束这段代码吗?
Is there anyway I can dry up this code?
推荐答案
是的,您可以使用Jquery.
Yes, You can do using Jquery.
$(input).attr(
{
"data-test-1": num1,
"data-test-2": num2
});
这篇关于您可以使用DOM的setAttribute函数设置多个属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文