浅学jQuery

59 阅读1分钟

一、获取元素

初步选取(tag、id、class)

    $(document) //选择整个文档对象

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

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

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

过滤操作

    $('div').has('p'); // 选择包含p元素的div元素

  $('div').not('.myClass'); //选择class不等于myClass的div元素

  $('div').filter('.myClass'); //选择class等于myClass的div元素

  $('div').first(); //选择第1个div元素

  $('div').eq(5); //选择第6个div元素

dom树上移动选择元素

    $('div').next('p'); //选择div元素后面的第一个p元素

  $('div').parent(); //选择div元素的父元素

  $('div').closest('form'); //选择离div最近的那个form父元素

  $('div').children(); //选择div的所有子元素

  $('div').siblings(); //选择div的同级元素

二、jQuery 的链式操作

$('div').find('h3').eq(2).html('Hello');
$('div') //找到div元素

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

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

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

jQuery还提供了.end()方法,使得结果集可以后退一步。对子元素操作后再回退,这种操作非常方便

$('div')

   .find('h3')

   .eq(2)

   .html('Hello')

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

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

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

三、创建元素

创建新元素的方法非常简单,只要把新元素直接传入jQuery的构造函数就行了:

    $('<p>Hello</p>');

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

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

四、移动元素

.insertAfter().after():在现存元素的外部,从后面插入元素

.insertBefore().before():在现存元素的外部,从前面插入元素

.appendTo().append():在现存元素的内部,从后面插入元素

.prependTo().prepend():在现存元素的内部,从前面插入元素   

五、修改元素属性

"取值器"与"赋值器"合一。到底是取值还是赋值,由函数的参数决定。

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

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

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

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

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

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

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

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