简体   繁体   中英

object oriented JS drop list?

i've created a button using OO JS which will be used to update something later on. I would also like to add a drop down menu/select list to my web app. The code i used for my button is:

    var AddButton = function(label){
    var _dom_element = document.createElement("input");
        _dom_element.type = "button";
        _dom_element.value = label;

        _dom_element.onclick = function(){
            //click_action.call(null);
            alert("Im Clicked");
        };
        this.getDomElement = function() {
            return _dom_element;
        }
    }

How do I change this code so it becomes a drop down menu/select list?

My best guess is that _dom_element.type = "select"; or something along those lines, however i havent got a clue what the actual type should equal.

Thanks for any help you can give.

You can try this

var AddSelect = function(options){
    var _dom_element = document.createElement("select");

    for ( var i = 0; i < options.length; i++ ) {
        var _option = document.createElement("option");
            _option.value = options[i];
            _option.innerHTML = options[i];

        _dom_element.appendChild(_option);
    }

    document.body.appendChild(_dom_element);

    _dom_element.onclick = function(){
        //click_action.call(null);
        //alert("Im Clicked");
    };
    this.getDomElement = function() {
        return _dom_element;
    }
}

AddSelect(['option1', 'option2', 'option3']);

DEMO

var AddSelect = function(options){
    var _dom_element = document.createElement("select");

    for ( var i = 0; i < options.length; i++ ) {
        var _option = document.createElement("option");
            _option.value = options[i];
            _option.innerHTML = options[i];

        _dom_element.appendChild(_option);
    }

    document.body.appendChild(_dom_element);

    _dom_element.onclick = function(){
        //click_action.call(null);
        //alert("Im Clicked");
    };
    this.getDomElement = function() {
        return _dom_element;
    }
}

AddSelect(['option1', 'option2', 'option3']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM