jQuery 如何获取元素
- 在jQuery中,将一个选择表达式,放进构造函数jQuery()(简写为$),然后就得到被选中的元素。比如:
$(document)
$('#myId')
$('div.myClass')
$('input[name=first]')
$('a:first')
$('tr:odd')
$('#myForm :input')
$('div:visible')
$('div:gt(2)')
$('div:animated')
jQuery 的链式操作
- 在jQuery中选中网页元素以后,可以对它进行一系列操作,并且所有操作可以连接在一起,称为链式操作;
$('div')
.find('h3')
.eq(2)
.html('Hello');
- 此外jQuery还提供了
.end()
方法,可以使得结果集退后一步;
$('div')
.find('h3')
.eq(2)
.html('Hello')
.end()
.eq(0)
.html('World');
jQuery创建元素
- 在jQuery中创建新元素的方法非常简单,只要把新元素直接传入jQuery的构造函数就行了:
$('<p>Hello</p>');
$('<li class="new">new list item</li>');
$('ul').append('<li>list item</li>');
jQuery移动元素
- jQuery提供两组方法,来操作元素在网页中的位置移动。一组方法是直接移动该元素,另一组方法是移动其他元素,使得目标元素达到我们想要的位置。
- 是使用
.insertAfter()
,把div元素移动p元素后面
$('div').insertAfter($('p'));
$('p').after($('div'));
jQuery 修改元素的属性
- jquery中用attr()方法来获取和设置元素属性,attr是attribute(属性)的缩写,是js中setAttribute()和getAttribute()的简化;
$("img").attr("src","img/a.jpg");
$("img").attr("width","100px");
$('img').attr({"width":80px, "height":50px});
$("img").attr("width",function(n,v){
return v-50;
});
$("img").removeAttr ("style");