栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

添加选项以使用javascript选择

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

添加选项以使用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的说法,其速度要快一些,但其他浏览器/平台的结果可能会有所不同。


*根据OP的评论进行了 *编辑

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415971.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号