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

标签 javascript arrays html button foreach

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

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

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

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

按钮:

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”就是这样。

任何指导都将受到高度赞赏:)

谢谢

最佳答案

这是一个简单的例子:

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

关于javascript - 如何根据数组中的对象数量创建按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42216594/

相关文章:

arrays - 如何使用nodejs在已经存在的文档中添加数组?

html - 标志的链接只有部分功能

javascript - 如何将 span 元素的内容更改为变量的内容

javascript - asp.net,javascript,无法获取属性 getElementsByTagName 的值

javascript - ASP.NET/IIS 将 302 响应重写为 200

javascript - 在 For in 循环中渲染复选框并在 Vue JS 中绑定(bind)它们的值

arrays - 合并两个 Eloquent Collections 并删除所有重复项。

javascript - 将绑定(bind)应用与数组参数一起使用时参数丢失

javascript - 单击时不会触发叠加层

javascript - 捕获 Drupal 自动完成值/事件并根据找到的结果更改表单组件