javascript在select指定位置插入option
在dhtml的DOM方法中有insertBefore方法,在浏览器下面可以使用此方法在指定的位置给select添加option对象。不过IE下调用insertBefore时,能添加option,但是创建的option对象设置的text属性会不显示,是空白,需要设置innerText属性来实现。
javascript在select指定位置插入option测试代码如下
<script type="text/javascript"> function Insert(){ var txt=document.getElementById('txt'),sel=document.getElementById('sel'); if(!/^\d+$/.test(txt.value)){alert('清输入数字!');txt.select();return false;} var idx=parseInt(txt.value,10),opt=document.createElement('option'); opt.innerText=opt.text=opt.value=new Date().getTime();//IE浏览器下调用insertBefore方法设置option的text无效,设置innerText可以。 if(idx>=sel.options.length)sel.options.add(opt); else sel.insertBefore(opt,sel.options[idx]); } </script> 插入位置[从0开始]:<input type="text" style="width:50px" id="txt"/><input type="button" value="插入option" onclick="Insert()" /><br/> <select size="10" id="sel"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select>
加支付宝好友偷能量挖...
原创文章,转载请注明出处:javascript在select指定位置插入option