我有一个选择字段,如下所示:
<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/