JQuery 操作select标签实现代码

时间:2021-05-26

下面几个常用的代码或许对您有帮助:
复制代码 代码如下:
//1.获取选中option值
$('#selectList').val();
//2.获取选中option的文本
$('#selectList :selected').text();
//3.获取多个选中option值、文本
var foo = [];
$('#multiple :selected').each(function(i, selected) {
foo[i] = $(selected).text();
});
// to get the selected values, just use .val() - this returns a string or array
foo = $('#multiple :selected').val();
//4.使用选项option的条件表达式
switch ($('#selectList :selected').text()) {
case 'First Option':
//do something
break;
case 'Something Else':
// do something else
break;
}
//5.删除某个value=2的option
$("#selectList option[value='2']").remove();
//6.从list A 移动option到 list B.
// here we have 2 select lists and 2 buttons. If you click the “add” button,
// we remove the selected option from select1 and add that same option to select2.
// The “remove” button just does things the opposite way around.
// Thanks to jQuery's chaining capabilities, what was once a rather tricky undertaking with JS can now be done in 6 lines of code.
$().ready(function() {
$('#add').click(function() {
return !$('#select1 option:selected').appendTo('#select2');
});
$('#remove').click(function() {
return !$('#select2 option:selected').appendTo('#select1');
});
});

如果您不了解JQuery,可以先看它的文档。

希望这篇POST对您有帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章