簡體   English   中英

如何根據數組中的對象數創建按鈕?

[英]How can i create buttons based on the number of objects in my array?

我有一個包含3個對象的數組

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

我想為每個這些對象創建一個按鈕。 我必須進行動態創建按鈕的原因是因為對象的數量會不時變化。

我如何遍歷每個對象並為其創建一個按鈕,然后將按鈕的工具提示設置為等於每個對象內的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”就是這樣。

任何指導將不勝感激:)

謝謝

這是一個簡單的示例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM