jQuery动态添加删除select项(实现代码)
时间:2024-04-22 12:59:04
// 添加
function col_add() {
var selObj = $("#mySelect");
var value="value";
var text="text";
selObj.append("<option value='"+value+"'>"+text+"</option>");
}
// 删除
function col_delete() {
var selOpt = $("#mySelect option:selected");
selOpt.remove();
}
// 清空
function col_clear() {
var selOpt = $("#mySelect option");
selOpt.remove();
}
以上方法为jQuery动态添加、删除和清空select。下面是纯js的写法:
var sid = document.getElementById("mySelect");
sid.options[sid.options.length]=new Option("text","value"); // 在select最后添加一项
其他常用的方法:
$("#mySelect").change(function(){//code...}); //select选中项改变时触发
// 获取select值
var text=$("#mySelect").find("option:selected").text(); //获取Select选中项的Text
var value=$("#mySelect").val(); //获取Select选中项的Value
var value=$("#mySelect option:selected").attr("value"); //获取Select选中项的Value
var index=$("#mySelect").get(0).selectedIndex; //获取Select选中项的索引值,从0开始
var index=$("#mySelect option:selected").attr("index"); //不可用!!!
var index=$("#mySelect option:selected").index(); //获取Select选中项的索引值,从0开始
var maxIndex=$("#mySelect option:last").attr("index"); //不可用!!!
var maxIndex=$("#mySelect option:last").index();//获取Select最大索引值,从0开始
$("#mySelect").prepend("<option value='value'>text</option>"); //Select第一项前插入一项
// 设置select值
//根据索引设置选中项
$("#mySelect").get(0).selectedIndex=index;//index为索引值
//根据value设置选中项
$("#mySelect").attr("value","newValue");
$("#mySelect").val("newValue");
$("#mySelect").get(0).value = value;
//根据text设置对应的项为选中项
var count=$("#mySelect option").length;
for(var i=0;i<count;i++)
{
if($("#mySelect").get(0).options[i].text == text)
{
$("#mySelect").get(0).options[i].selected = true;
break;
}
}
// 清空select
$("#mySelect").empty();
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Golang实现HTTP编程请求和响应
![](https://img.aspxhome.com/file/2023/2/134312_0s.jpg)
网页屏蔽鼠标左右键和键盘按键功能
Python运算符之Inplace运算符的使用教程
如何在nodejs中体验http/2详解
![](https://img.aspxhome.com/file/2023/1/129341_0s.jpg)
Git Submodule使用完整教程(小结)
基于mpvue的小程序项目搭建的步骤
![](https://img.aspxhome.com/file/2023/0/126450_0s.jpg)
对python中的乘法dot和对应分量相乘multiply详解
框架布局慎用元素
Python实现获取网页内容及自动填表单与登录功能
![](https://img.aspxhome.com/file/2023/6/124936_0s.png)
解决Alexnet训练模型在每个epoch中准确率和loss都会一升一降问题
![](https://img.aspxhome.com/file/2023/5/107785_0s.jpg)
CSS控制鼠标样式变换方法
pandas将list数据拆分成行或列的实现
![](https://img.aspxhome.com/file/2023/9/72069_0s.png)
Python中字符串对象语法分享
![](https://img.aspxhome.com/file/2023/9/75959_0s.gif)
SQL Server 2005 更改安装路径目录的方法小结
![](https://img.aspxhome.com/file/2023/8/104128_0s.gif)
vue实现拖拽效果
![](https://img.aspxhome.com/file/2023/1/130081_0s.jpg)
实现Python3数组旋转的3种算法实例
Pandas中Series的属性,方法,常用操作使用案例
![](https://img.aspxhome.com/file/2023/1/83771_0s.png)
Python聊天室实例程序分享
![](https://img.aspxhome.com/file/2023/3/133323_0s.gif)
HTTP状态码
利用Pandas索引和选取数据方法详解
![](https://img.aspxhome.com/file/2023/4/127924_0s.png)