使用 JavaScript 一次为一个元素设置多个属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12274748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting multiple attributes for an element at once with JavaScript
提问by JP Silvashy
How can I set multiple attributes at once with JavaScript? Unfortunately, I'm not able to use a framework like jQuery on this project. Here is what I have now:
如何使用 JavaScript 一次设置多个属性?不幸的是,我无法在这个项目中使用像 jQuery 这样的框架。这是我现在所拥有的:
var elem = document.createElement("img");
elem.setAttribute("src", "http://example.com/something.jpeg");
elem.setAttribute("height", "100%");
elem.setAttribute("width", "100%");
回答by Ariel
You could make a helper function:
你可以做一个辅助功能:
function setAttributes(el, attrs) {
for(var key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
Call it like this:
像这样调用它:
setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});
回答by webdevkit
You might be able to use Object.assign(...)
to apply your properties to the created element. See comments for additional details.
您也许可以使用Object.assign(...)
将您的属性应用于创建的元素。有关其他详细信息,请参阅评论。
Keep in mind that height
and width
attributes are defined in pixels, not percents. You'll have to use CSS to make it fluid.
请记住,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 }
回答by jfriend00
You can create a function that takes a variable number of arguments:
您可以创建一个接受可变数量参数的函数:
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%"
});
You could also make your own chainable object wrapper/method:
您还可以制作自己的可链接对象包装器/方法:
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%");
Working example: http://jsfiddle.net/jfriend00/qncEz/
回答by Chris Baker
If you wanted a framework-esq syntax (Note:IE 8+ support only), you could extend the Element
prototype and add your own setAttributes
function:
如果您需要 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]);
}
}
};
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'
});
Try it: http://jsfiddle.net/ywrXX/1/
试试看:http: //jsfiddle.net/ywrXX/1/
If you don't like extending a host object (some are opposed) or need to support IE7-, just use it as a function
如果你不喜欢扩展一个宿主对象(有些人反对)或者需要支持 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.
请注意,setAttribute
这不适用于style
IE 或事件处理程序(无论如何您都不应该这样做)。上面的代码处理style
,但不处理事件。
Documentation
文档
- Object prototypes on MDN - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/prototype
setAttribute
on MDN - https://developer.mozilla.org/en-US/docs/DOM/element.setAttribute
回答by danactive
You could code an ES5.1 helper function:
你可以编写一个 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%' });
回答by KooiInc
Or create a function that creates an element including attributes from parameters
或者创建一个函数来创建一个包含参数属性的元素
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');
FYI: height/width='100%'
would not work using attributes. For a height/width of 100% you need the elements style.height/style.width
仅供参考:height/width='100%'
使用属性不起作用。对于 100% 的高度/宽度,您需要元素style.height/style.width
回答by Geek Devigner
const setAttributes = (el, attrs) =>
Object.entries(attrs)
.forEach(args =>
el.setAttribute(...args))
回答by Slawe
回答by Slawe
use this function to create and set attributes at the same time
使用此函数同时创建和设置属性
function createNode(node, attributes){
const el = document.createElement(node);
for(let key in attributes){
el.setAttribute(key, attributes[key]);
}
return el;
}
use it like so
像这样使用它
const input = createNode('input', {
name: 'test',
type: 'text',
placeholder: 'Test'
});
document.body.appendChild(input);
回答by Dr JavaB
I guess it's best way to set attributes at once for any element in this class.
我想这是为此类中的任何元素一次设置属性的最佳方式。
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);