您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

添加选项以使用javascript选择

添加选项以使用javascript选择

您可以通过一个简单的for循环来实现:

var min = 12,
    max = 100,
    select = document.getElementById('selectElementId');

for (var i = min; i<=max; i++){
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = i;
    select.appendChild(opt);
}

JS Perf比较了我和imeVidas的答案,是因为我认为他的表情比我的看起来更容易理解/直观,而且我想知道这将如何转化为实现。根据Chromium14/Ubuntu11.04的说法,其速度要快一些,但其他浏览器/平台的结果可能会有所不同。

[如何] [我]将此应用于多个元素?

function populateSelect(target, min, max){
    if (!target){
        return false;
    }
    else {
        var min = min || 0,
            max = max || min + 100;

        select = document.getElementById(target);

        for (var i = min; i<=max; i++){
            var opt = document.createElement('option');
            opt.value = i;
            opt.innerHTML = i;
            select.appendChild(opt);
        }
    }
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);

// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');

// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);

最后,(经过相当长的延迟之后),一种方法扩展了原型,HTMLSelectElement以便将populate()函数作为一种方法链接到DOM节点:

HTMLSelectElement.prototype.populate = function (opts) {
    var settings = {};

    settings.min = 0;
    settings.max = settings.min + 100;

    for (var userOpt in opts) {
        if (opts.hasOwnProperty(userOpt)) {
            settings[userOpt] = opts[userOpt];
        }
    }

    for (var i = settings.min; i <= settings.max; i++) {
        this.appendChild(new Option(i, i));
    }
};

document.getElementById('selectElementId').populate({
    'min': 12,
    'max': 40
});
javascript 2022/1/1 18:13:41 有726人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶