如何使用 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%");
您可以创建一个辅助函数:
function setAttributes(el, attrs) {
for(var key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
像这样称呼它:
setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});
您可能可以使用Object.assign(...)
将您的属性应用于创建的元素。尽管某些“属性(elem.height 等)是只读的,即只有一个 getter(未定义的 setter)的访问器”。
请记住,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
不适用于style
IE 或事件处理程序(无论如何您都不应该这样做)。上面的代码处理style
,但不处理事件。
文档
你可以编写一个 ES5.1 辅助函数:
function setAttributes(el, attrs) {
Object.keys(attrs).forEach(key => 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%");
或者,您将属性/值对传递给对象:
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/
const setAttributes = (el, attrs) =>
Object.entries(attrs)
.forEach(args =>
el.setAttribute(...args))
或者创建一个函数来创建一个包含参数属性的元素
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
试试这个
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;
}
演示:这里
您可以简单地将一个方法(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 语句以引发错误。
无功能示例:
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);
}
使用此功能同时创建和设置属性
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);
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]);
}