如何使用JavaScript一次设置多个属性?不幸的是,我无法在该项目上使用类似jQuery的框架。这是我现在所拥有的:
var elem = document.createElement("img");
elem.setAttribute("src", "http://example.com/something.jpeg");
elem.setAttribute("height", "100%");
elem.setAttribute("width", "100%");
如何使用JavaScript一次设置多个属性?不幸的是,我无法在该项目上使用类似jQuery的框架。这是我现在所拥有的:
var elem = document.createElement("img");
elem.setAttribute("src", "http://example.com/something.jpeg");
elem.setAttribute("height", "100%");
elem.setAttribute("width", "100%");
Answers:
您可以创建一个辅助函数:
function setAttributes(el, attrs) {
for(var key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
这样称呼它:
setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});
elem.setAttribute()。
您可能可以使用Object.assign(...)将属性应用于创建的元素。有关更多详细信息,请参见评论。
请记住,height和width属性是以像素而不是百分比定义的。您必须使用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 }
如果要使用framework-esq语法(注意:仅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]);
}
}
};
这使您可以使用如下语法:
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-,只需将其用作函数即可
请注意,setAttribute这不适用于styleIE或事件处理程序(无论如何都不应该)。上面的代码处理style,但不处理事件。
文献资料
setAttribute在MDN上-https: //developer.mozilla.org/zh-CN/docs/DOM/element.setAttribute'Element' is undefined
document.createElement并document.getElementById填充此....,也可以将功能包装在一个函数中。编辑答案以包括该注释
您可以创建一个带有可变数量参数的函数:
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%");
或者,您将属性/值对传递给对象:
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%");
或创建一个函数来创建一个包含参数中的属性的元素
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
clone方法将是首选。无需从头开始创建整个节点。无论如何,最小化对DOM(最常见的用例)的访问是头等大事。
使用此功能同时创建和设置属性
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);
您只需在“元素”原型中添加一个方法(setAttributes,末尾带有“ 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语句以引发错误。
Object.assign()值得一看,那些不想创建帮助函数的对象-适用于“所有可枚举和自己的属性”。