动态填充html select tag的options

时间:2021-08-01 00:05:19

用AMD模块写了一额select.js,用来帮助我动态创建options,并选中其中一个。

调用代码参考例子:

        var s5 = this.select.create();
s5.bind("s5");
s5.addOption(0, "GMT+0");
s5.addOption(1, "GMT-8");
s5.addOption(2, "GMT+8");
s5.choose(1);

select.js源代码:

define("select", ["jquery"], function ($) {'use strict';return {// create a selector objectcreate: function () {    var innerSelect = {id: "",// using JQuery slector to set the inner HTML codesbind: function(id) {    this.id = id;},// add an option which contains value and textaddOption: function(value, text) {    var t, option;    t = "<option value={0}>{1}</option>";    option = jQuery.validator.format(t, value, text);    $("#" + this.id).append(option);},// select one existing optionchoose: function(value) {    $("#" + this.id).val(value);    }    };    return innerSelect;}};});

不用AMD的人可以将代码稍微修改一下。