逃不开传统的四种操作:增、删、改、查。
[增]:
复制代码 代码如下:
$(#select_id).append(text); //为select追加一个option(下拉项)
$(#select_id).prepend(请选择); //为select插入一个option(第一个位置)
[删]:
复制代码 代码如下:
$(#select_id option:last).remove(); //删除select中索引值最大option(最后一个)
$(#select_id option[index='0']).remove(); //删除select中索引值为0的option(第一个)
$(#select_id option[value='3']).remove(); //删除select中value='3'的option
$(#select_id option[text='4']).remove(); //删除select中text='4'的option
$(#select_id).empty(); //清空
[改](设置选中项):
复制代码 代码如下:
$(#select_id ).get(0).selectedindex=1; //设置select索引值为1的项选中
$(#select_id ).val(4); //设置select的value值为4的项选中
$(#select_id option[text='jquery']).attr(selected, true); //设置select的text值为jquery的项选中
[查](获取选中值):
1.获取选中项的value
复制代码 代码如下:
$(#select_id).val(); //获取选中项的value
$(#select_id ).get(0).selectedindex; //获取选中项的索引值
$(#select_id).find(option:selected).text(); //获取选中项的text
$(#select_id option:last).attr(index); //获取select最大的索引值
附上代码样例,代码功能为根据实际选择的“年”、“月”,来改变select“日”中option的天数。
使用php编写,默认$(select.day)初始有31天,因为默认为1月:
复制代码 代码如下:
//年
for ($year = 1990; $year ?>
}
?>
复制代码 代码如下:
//月
for ($month = 1; $month ?>
}
?>
复制代码 代码如下:
//日
for ($day = 1; $day ?>
}
?>
jquery代码:
复制代码 代码如下:
$(document).ready(function() {
$(select.month, select.year).change(function() { //年、月的变化都可能引起“日”的变化
$(select.day).empty(); //非常重要,要先清空
for (var i = 1; i var option = $().val(i).text(i);
$(select.day).append(option);
}
var month = $(select.month).val();
if ((month % 2 && month 7)) {
$(select.day).append(31); //天数为31天的append一个option
}
if (month === 2) {
$(select.day option:last).remove();
$(select.day option:last).remove(); //2月天数28
var year = $(select.year).val();
if ((year % 4 === 0 && year % 100) || year % 400 === 0)
$(select.day).append(29); //闰年2月天数加一
}
});
});
以上就是关于jquery实现对select的增、删、改、查操作总结,希望大家能够喜欢。