使用 JavaScript 一次为元素设置多个属性

如何使用 JavaScript 一次设置多个属性?不幸的是,我不能在这个项目中使用像 jQuery 这样的框架。以下是我现在拥有的:

var elem = document.createElement("img");


elem.setAttribute("src", "http://example.com/something.jpeg");
elem.setAttribute("height", "100%");
elem.setAttribute("width", "100%");
211457 次浏览

你可以创建一个 helper 函数:

function setAttributes(el, attrs) {
for(var key in attrs) {
el.setAttribute(key, attrs[key]);
}
}

这么说吧:

setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});

您可以创建一个带有可变数量参数的函数:

function setAttributes(elem /* attribute, value pairs go here */) {
for (var i = 1; i < arguments.length; i+=2) {
elem.setAttribute(arguments[i], arguments[i+1]);
}
}


setAttributes(elem,
"src", "http://example.com/something.jpeg",
"height", "100%",
"width", "100%");

Or, you pass the attribute/value pairs in on an object:

 function setAttributes(elem, obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
elem[prop] = obj[prop];
}
}
}


setAttributes(elem, {
src: "http://example.com/something.jpeg",
height: "100%",
width: "100%"
});

你也可以制作你自己的链式对象包装器/方法:

function $$(elem) {
return(new $$.init(elem));
}


$$.init = function(elem) {
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
this.elem = elem;
}


$$.init.prototype = {
set: function(prop, value) {
this.elem[prop] = value;
return(this);
}
};


$$(elem).set("src", "http://example.com/something.jpeg").set("height", "100%").set("width", "100%");

工作示例: http://jsfiddle.net/jfriend00/qncEz/

如果你想要一个框架-esq 语法(仅支持 Note: IE 8 +) ,你可以扩展 Element原型并添加你自己的 setAttributes函数:

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]);
}
}
};

This lets you use syntax like this:

var d = document.createElement('div');
d.setAttributes({
'id':'my_div',
'class':'my_class',
'styles':{
'backgroundColor':'blue',
'color':'red'
},
'html':'lol'
});

试试: http://jsfiddle.net/ywrXX/1/

如果你不喜欢扩展一个主机对象(有些人反对)或者需要支持 IE7-,那么就把它当作一个函数来使用

Note that setAttribute will not work for style in IE, or event handlers (you shouldn't anyway). The code above handles style, but not events.

文件

或者创建一个函数,该函数创建一个包含来自参数的属性的元素

function elemCreate(elType){
var element = document.createElement(elType);
if (arguments.length>1){
var props = [].slice.call(arguments,1), key = props.shift();
while (key){
element.setAttribute(key,props.shift());
key = props.shift();
}
}
return element;
}
// usage
var img = elemCreate('img',
'width','100',
'height','100',
'src','http://example.com/something.jpeg');

供参考: height/width='100%'不能使用属性。如果高度/宽度为100% ,则需要使用元素 style.height/style.width

Try this

function setAttribs(elm, ob) {
//var r = [];
//var i = 0;
for (var z in ob) {
if (ob.hasOwnProperty(z)) {
try {
elm[z] = ob[z];
}
catch (er) {
elm.setAttribute(z, ob[z]);
}
}
}
return elm;
}

演示: HERE

您可以编写 ES5.1助手函数:

function setAttributes(el, attrs) {
Object.keys(attrs).forEach(key => el.setAttribute(key, attrs[key]));
}

Call it like this:

setAttributes(elem, { src: 'http://example.com/something.jpeg', height: '100%' });

您可以使用 Object.assign(...)将属性应用于创建的元素。尽管一些“属性(elem.height 等)是只读的,即只有一个 getter (未定义 setter)的访问器。”

请记住,heightwidth属性是 defined in pixels,而不是百分比。你必须使用 CSS 使其流动。

var elem = document.createElement('img')
Object.assign(elem, {
className: 'my-image-class',
src: 'https://dummyimage.com/320x240/ccc/fff.jpg',
height: 120, // pixels
width: 160, // pixels
onclick: function () {
alert('Clicked!')
}
})
document.body.appendChild(elem)


// One-liner:
// document.body.appendChild(Object.assign(document.createElement(...), {...}))
.my-image-class {
height: 100%;
width: 100%;
border: solid 5px transparent;
box-sizing: border-box
}


.my-image-class:hover {
cursor: pointer;
border-color: red
}


body { margin:0 }

const setAttributes = (el, attrs) =>
Object.entries(attrs)
.forEach(args =>
el.setAttribute(...args))

使用此函数同时创建和设置属性

function createNode(node, attributes){
const el = document.createElement(node);
for(let key in attributes){
el.setAttribute(key, attributes[key]);
}
return el;
}

像这样使用它

const input = createNode('input', {
name: 'test',
type: 'text',
placeholder: 'Test'
});
document.body.appendChild(input);

我想这是立即为这个类中的任何元素设置属性的最佳方法。

function SetAtt(elements, attributes) {
for (var element = 0; element < elements.length; element++) {
for (var attribute = 0; attribute < attributes.length; attribute += 2) {
elements[element].setAttribute(attributes[attribute], attributes[attribute + 1]);
}
}
}
var Class = document.getElementsByClassName("ClassName"); // class array list
var Data = ['att1', 'val1', 'att2', 'val2', 'att3', 'val3']; //attributes array list
SetAtt(Class, Data);

您可以简单地向“ Element”原型添加一个方法(setAttritribute,末尾带有“ s”) ,比如:

Element.prototype.setAttributes = function(obj){
for(var prop in obj) {
this.setAttribute(prop, obj[prop])
}
}

你可以用一行来定义它:

Element.prototype.setAttributes = function(obj){ for(var prop in obj) this.setAttribute(prop, obj[prop]) }

你可以像调用其他方法一样调用它,属性是作为一个对象给出的:

elem.setAttributes({"src": "http://example.com/something.jpeg", "height": "100%", "width": "100%"})

如果给定的参数不是对象,则可以添加 if 语句来引发错误。

无函数示例 :

let checkbox = document.createElement('input');


for (const [key, value] of Object.entries({
type: 'checkbox',
id: 'sys-surname',
class: 'switcher23',
value: 1,
name: 'surname'
})) {
checkbox.setAttribute(key, value);
}
let elem = document.createElement("img");
Object.entries({"src": "http://example.com/something.jpeg"),
"height": "100%",
"width": "100%"}).forEach(kv => elem.setAttribute(kv[0], kv[1]));

这是个简单的方法

let div = document.getElementsByTagName("div")[0];


let attr = ["class", "id", "title"];
let attrVlu = ["ahmed", "mohamed", "ashraf"];


for(let i = 0; i < 3; i++) {
div.setAttribute(attr[i], attrVlu[i]);
}

最简单的: ` Var elem = document.createElement (“ img”) ;

Var attrs = { Http://example.com/something.jpeg" 身高: “100%”, 宽度: 「100% 」 }

赋值(elem,attrs) ; `

var elem = document.createElement("img");


function setAttributes(attributes) {
for (let key in attributes) {
elem.setAttribute(key, attributes[key]);
}
}






setAttributes({src: "http://example.com/something.jpeg",height: "100%",width: "100%",});

最简单的方法是:

创建一个包含对象的数组,比如: Array = [{ ob1} ,{ ob2}等等... ]

接下来,对 array 进行迭代以设置键的对象,如

属性和值的对象,如属性的值:

例如: let arr = [{'id': 'myId'}, {'class': 'myClassname'}]

/在数组上迭代/

function setAt(array){


for (attr of array){
myElement.setAttribute(attr, array[attr])
}
}

然后,像 args 一样调用传递数组的函数: SetAt (arr)