我们经常遇到要操作DOM元素,例如<select>,在Asp.net中Dropdownlist原型就是select。下面几个常用的代码或许对您有帮助:
1: //1.获取选中option值
2: $('#selectList').val();
3:
4: //2.获取选中option的文本
5: $('#selectList :selected').text();
6:
7:
8: //3.获取多个选中option值、文本
9: var foo = [];
10: $('#multiple :selected').each(function(i, selected) {
11: foo[i] = $(selected).text();
12: });
13: // to get the selected values, just use .val() - this returns a string or array
14: foo = $('#multiple :selected').val();
15:
16:
17: //4.使用选项option的条件表达式
18: switch ($('#selectList :selected').text()) {
19: case 'First Option':
20: //do something
21: break;
22: case 'Something Else':
23: // do something else
24:
25: break;
26: }
27:
28: //5.删除某个value=2的option
29: $("#selectList option[value='2']").remove();
30:
31:
32: //6.从list A 移动option到 list B.
33: // here we have 2 select lists and 2 buttons. If you click the “add” button,
34: // we remove the selected option from select1 and add that same option to select2.
35: // The “remove” button just does things the opposite way around.
36: // Thanks to jQuery’s chaining capabilities, what was once a rather tricky undertaking with JS can now be done in 6 lines of code.
37: $().ready(function() {
38: $('#add').click(function() {
39: return !$('#select1 option:selected').appendTo('#select2');
40: });
41: $('#remove').click(function() {
42: return !$('#select2 option:selected').appendTo('#select1');
43: });
44: });
如果您不了解JQuery,可以先看它的文档。
希望这篇POST对您有帮助。
Author: Petter Liu http://www.cnblogs.com/wintersun