1

我想通过单击按钮添加通过 JavaScript 动态选择的选项。我想确保它是否已经存在 n 选项,然后它仅在 n+1 选项位置添加。

<select name="select">
 <option value="value1">Value 1</option> 
 <option value="value2" selected>Value 2</option>
 <option value="value3">Value 3</option>
</select>
<button onclick =addvalue()>clickme</button>enter code here
function addvalue()
 {
  var e=document.getElementById('select');
  var i =0;
  var abc = true;
  while(abc)
  {
   if (e.options[i].innerText==null)
   {
    abc =false;
   }
   i++;
 }
 alert(i);
}

但这会引发错误,即 e.options[i].innerText 为空或不是对象。我将用代码替换警报,以便稍后添加选项

4

3 回答 3

1

e.options[i].innerText 为空或不是对象

因为没有什么options[i]时候i >= options.length。检查它是否存在:

function addvalue()
 {
  var e=document.getElementById('select');
  var i =0;
  var abc = true;
  while(abc)
  {
   if (!e.options[i] || e.options[i].innerText==null)
   {
    abc =false;
   }
   i++;
  }
  alert(i);
}

http://jsfiddle.net/eMQzC/

它会提醒4,我不确定你想要得到什么。设置为i后增加一次。abcfalse

我认为您可能根本不需要那个while循环。

function addvalue()
 {
  var e=document.getElementById('select'), i = e.options.length;
  alert(i);
}

这将提醒3,因为它是您选择的选项数量。

于 2013-09-18T07:26:53.170 回答
1

您正在使用 document.getElementBy Id ('select');,但指定了select 的名称。将 'name' 更改为 'id',你应该会很好,尽管我推荐一些比“select”更具描述性的东西:)

例如从<select name="select"><select id="select">

于 2013-09-18T06:56:44.237 回答
0

如果您使用 getElementByID API,您需要获取一个 id。为选择添加一个“id”属性,然后你就得到了你的元素。

使用浏览器的开发者工具(chrome - f12)来调试你的代码。如果添加调试器;声明它将自动停止。

于 2013-09-18T06:59:38.423 回答