【问题标题】:How can i create buttons based on the number of objects in my array?如何根据数组中的对象数量创建按钮?
【发布时间】:2017-07-02 04:17:17
【问题描述】:

我有一个包含 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”就是这样。

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

谢谢

【问题讨论】:

    标签: javascript arrays html button foreach


    【解决方案1】:

    这是一个简单的例子:

    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,并且必须使用上述“this._selectionbutt”。
    猜你喜欢
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    相关资源
    最近更新 更多