如何根据数组中的对象数创建按钮?

时间:2017-02-14 01:58:14

标签: javascript arrays html5 button foreach

我有一个包含3个对象的数组

map.la = [object, object, object];

我想为每个对象创建一个按钮。我必须dybamicaly创建按钮的原因是因为对象的数量 不时变化。

如何遍历每个对象并为其创建一个按钮,然后将按钮的工具提示设置为等于每个对象内的name属性?

按钮:

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();
});

一旦用户选择按钮中的任何一个按钮,它们将被带到相同的功能(this._handleSelection())和此功能 将需要检查名称属性字符串,例如“map333”就是这样。

任何指导都会高度评价:)

谢谢

1 个答案:

答案 0 :(得分:0)

这是一个简单的例子:

HTML代码。创建div,我们将添加按钮

<div id="buttons"></div>

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);
 } );