[英]How can i create buttons based on the number of objects in my array?
I have an array with 3 objects 我有一个包含3个对象的数组
map.la = [object, object, object];
I want to create a button for each of these objects. 我想为每个这些对象创建一个按钮。 The reason i have to dybamicaly create the buttons is because the number of objects varies from time to time. 我必须进行动态创建按钮的原因是因为对象的数量会不时变化。
How can i loop through each object and create a button for it and then set the tooltip of the button to equal the name property inside each object? 我如何遍历每个对象并为其创建一个按钮,然后将按钮的工具提示设置为等于每个对象内的name属性?
the button: 按钮:
this._selectionbutt = new SegButton({
items: [
//each of the below items (this.selection) should be added here to items array. because we have 3 buttons there
//should be three unique items here. the items should have the same name as the variable we instantiate the
//button with.
this._oSelection
]
});
this.selection = new SegButtItems({
icon: "map",
tooltip: //this should be the name property of each item
press: this._handleSelection();
});
Once the user selects the button any of the buttons they will be taken to the same function (this._handleSelection()) and this function will need to check the name property string eg "map333" and thats it. 一旦用户选择了按钮中的任何一个,它们将被带到相同的功能(this._handleSelection()),并且该功能将需要检查名称属性字符串,例如“ map333”就是这样。
Any guidance will be highly appreicated :) 任何指导将不胜感激:)
Thank you 谢谢
Here is a simple example: 这是一个简单的示例:
HTML code. HTML代码。 Create div, to wich we will add buttons 创建div,至此我们将添加按钮
<div id="buttons"></div>
Js code: js代码:
//create objects
var Object1 = {
icon: "map",
tooltip: "Press Me",
press: 'console.log("Button1 pressed")'
};
var Object2 = {
icon: "map",
tooltip: "Press Me",
press: 'console.log("Button2 pressed")'
};
var Object3 = {
icon: "map",
tooltip: "Press Me",
press: 'console.log("Button3 pressed")'
};
//add objects to array
var ar = [Object1, Object2, Object3];
//add buttons for every object in array
ar.forEach( function(v) {
var button= document.createElement('button');
button.type= 'button';
button.appendChild(document.createTextNode(v.tooltip));
button.setAttribute('onClick',v.press);
document.getElementById("buttons").appendChild(button);
} );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.