javascript - 替换选择字段中的选项(不添加)

标签 javascript html regex

我有一个选择字段,如下所示:

<select id="field">

我根据页面上另一个 div (OtherDiv) 中找到的值添加选项,如下所示:

window.onload = function onload()
    {
        var OtherDiv = document.getElementById('OtherDiv').innerHTML;
        var result = OtherDiv.match(/SomeRegex/gi);
        var select = document.getElementById("field");
        for(var i = 0; i < result.length; i++)
            {
                var option = document.createElement("option");
                option.value = i+1;
                option.innerHTML = result[i];
                select.add(option);
            }
    }

但是,如果正则表达式没有匹配项,我想为要显示的字段设置一些替代值。我怎样才能最好地实现这一目标?

最佳答案

使用if条件

window.onload = function onload()
{
    var OtherDiv = document.getElementById('OtherDiv').innerHTML;
    var result = OtherDiv.match(/SomeRegex/gi);
    var select = document.getElementById("field");
    if(result.length){
        for(var i = 0; i < result.length; i++)
            {
                var option = document.createElement("option");
                option.value = i+1;
                option.innerHTML = result[i];
               select.add(option);
            }
      }else{
           //add alternative options here
           var option = document.createElement("option");
                option.innerHTML = "No records found"; //whatever text you want to show 
               select.add(option);
      }
}

关于javascript - 替换选择字段中的选项(不添加),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32133257/

相关文章:

javascript - 如何使用按钮允许用户添加/减去输入元素并保持元素值顺序?

javascript - 在 phonegap android 应用程序中加载下一页时显示加载程序图像

javascript - 查找上一个 <a> 元素?

javascript - 不透明背景中的非不透明文本

javascript - 如何通过两次单击在两个方向上旋转图标?

javascript - Jinja2 和 HTML Div 标签

python - 多行正则表达式

javascript - 使用正则表达式捕获换行符后的下一行文本

javascript - 为什么计算的日期在 Internet Explorer 和 Chrome 中不同?

javascript - 如何只在字符/之前显示日期?