[英]Setting multiple attributes for an element at once with JavaScript
如何使用 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
不適用於 IE 中的style
或事件處理程序(無論如何您都不應該這樣做)。 上面的代碼處理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);
}
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]));
使用此功能同時創建和設置屬性
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 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");
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 = [{obj1}, {obj2}, etc...]
接下來,您迭代數組以設置密鑰的 object 就像
屬性和值的 object 就像屬性的值:
示例:讓 arr = [{'id': 'myId'}, {'class': 'myClassname'}]
/迭代數組/
function setAt(array){
for (attr of array){
myElement.setAttribute(attr, array[attr])
}
}
稍后,您調用 function 像 args 一樣傳遞您的數組: setAt(arr)
最簡單的:` var elem = document.createElement("img");
var attrs = { src:“http://example.com/something.jpeg”,高度:“100%”,寬度:“100%”}
Object.assign(elem, attrs); `
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.