javascript select work

本文介绍了一种使用JavaScript来操作HTML中的Select元素的方法,包括在选定项前插入选项、移除选定选项、在末尾追加选项及移除最后一个选项等功能,并提供了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

样式:(本页中操作不起作用,只为原型,其脚与html请看 示例下一个)

 Insert Before Selected
 Remove Selected
Append5Append6Append7Append8Append10Append11Append12Append13Append14Append15
 Append Last
 Remove Last

 

The JavaScript
<script language="JavaScript" type="text/javascript">
var count1 = 0;
var count2 = 0;
function insertOptionBefore(num)
{
    var diabloselect = document.getElementById('selectX'); 
 if (diabloselect.selectedIndex >= 0)
 {
        var selectoption = document.createElement('option');   
  selectoption.text = 'Insert' + num;   
  selectoption.value = 'insert' + num;   
  var currentoption = diabloselect.options[diabloselect.selectedIndex];  //current index   
  try
  {     
      diabloselect.add(selectoption, currentoption); // standards compliant; doesn't work in IE   
  }   
  catch(ex)
  {     
      diabloselect.add(selectoption, diabloselect.selectedIndex); // IE only   
  } 
 }
}
function removeOptionSelected()

    var diabloselect = document.getElementById('selectX'); 
 var i; 
 for (i = diabloselect.length - 1; i>=0; i--)
 {   
     if (diabloselect.options[i].selected)
  {     
      diabloselect.remove(i);   
  } 
 }
}
function appendOptionLast(num)

    var selectoption = document.createElement('option'); 
 selectoption.text = 'Append' + num; 
 selectoption.value = 'append' + num; 
 var diabloselect = document.getElementById('selectX'); 
 try
 {   
     diabloselect.add(selectoption, null); // standards compliant; doesn't work in IE 
 } 
 catch(ex)
 {   
     diabloselect.add(selectoption); // IE only 
 }
}
function removeOptionLast()

    var diabloselect = document.getElementById('selectX'); 
 if (diabloselect.length > 0) 
 {   
     diabloselect.remove(diabloselect.length - 1); 
 }
}
</script>
 
The HTML
<form>
<input type="button" value="o" onclick="insertOptionBefore(count1++);" />Insert Before Selected<br />
<input type="button" value="o" onclick="removeOptionSelected();" />Remove Selected<br />
<select id="selectX" size="10" multiple="multiple">
<option value="original1" selected="selected">Orig1</option>
<option value="original2">Orig2</option></select><br />
<input type="button" value="o" onclick="appendOptionLast(count2++);" />Append Last<br />
<input type="button" value="o" onclick="removeOptionLast();" />Remove Last
</form>
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值