jQuery 的功能

1、jQuery 如何获取元素

1.1 选择表达式可以是CSS选择器:

1
2
3
4
5
6
7
 $(document) //选择整个文档对象

 $('#myId') //选择ID为myId的网页元素

 $('div.myClass') // 选择class为myClass的div元素

 $('input[name=first]') // 选择name属性等于first的input元素

1.2 jQuery特有的表达式:

1
2
3
4
5
6
7
8
9
10
11
$('a:first') //选择网页中第一个a元素

$('tr:odd') //选择表格的奇数行

$('#myForm :input') // 选择表单中的input元素

$('div:visible') //选择可见的div元素

$('div:gt(2)') // 选择所有的div元素,除了前三个

$('div:animated') // 选择当前处于动画状态的div元素

2、jQuery 的链式操作是怎样的

1
$('div').find('h3').eq(2).html('Hello');

分解开来,就是下面这样:

1
2
3
4
5
6
7
 $('div') //找到div元素

   .find('h3') //选择其中的h3元素

   .eq(2) //选择第3个h3元素

   .html('Hello'); //将它的内容改为Hello

jQuery还提供了.end()方法,使得结果集可以后退一步:

1
2
3
4
5
6
7
8
9
10
11
12
13
  $('div')

   .find('h3')

   .eq(2)

   .html('Hello')

   .end() //退回到选中所有的h3元素的那一步

   .eq(0) //选中第一个h3元素

   .html('World'); //将它的内容改为World

3、jQuery 如何创建元素

1
2
3
4
5
$('<p>Hello</p>');

$('<li class="new">new list item</li>');

$('ul').append('<li>list item</li>');

4、jQuery 如何移动元素

假定我们选中了一个div元素,需要把它移动到p元素后面。
第一种方法是使用.insertAfter(),把div元素移动p元素后面:

1
$('div').insertAfter($('p'));

第二种方法是使用.after(),把p元素加到div元素前面:

1
 $('p').after($('div'));

5、jQuery 取值和赋值

1
2
3
$('h1').html(); //html()没有参数,表示取出h1的值

$('h1').html('Hello'); //html()有参数Hello,表示对h1进行赋值

常见的取值和赋值函数如下:

1
2
3
4
5
6
7
8
9
10
11
 .html() 取出或设置html内容

 .text() 取出或设置text内容

 .attr() 取出或设置某个属性的值

 .width() 取出或设置某个元素的宽度

 .height() 取出或设置某个元素的高度

 .val() 取出某个表单元素的值