程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了添加选项以使用javascript选择大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决添加选项以使用javascript选择?

开发过程中遇到添加选项以使用javascript选择的问题如何解决?下面主要结合日常开发的经验,给出你关于添加选项以使用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在id =“ mainSelect”的选择中创建12到100个选项,因为我不想手动创建所有选项标签。你能给我一些指导吗?谢谢

function selectOptionCreate() {

  var age = 88;
  line = "";
  for (var i = 0; i < 90; i++) {
    line += "<option>";
    line += age + i;
    line += "</option>";
  }

  return line;
}

大佬总结

以上是大佬教程为你收集整理的添加选项以使用javascript选择全部内容,希望文章能够帮你解决添加选项以使用javascript选择所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: