3.1 JQuery的Dom操作
1、使用html()方法读取或者设置元素的innerHTML:
alert($("#btn1").html()); $("#btn1").html("hello"); 2、使用text()方法读取或者设置元素的innerText: alert($("#btn1").text()); $("#btn1").text("hello"); 3、使用attr()方法读取或者设置元素的属性,对于JQuery没有封装的属性(所有浏览器没有差异的属性)用attr进行操作。 alert($(“#btn1").attr("href")); $("#btn1").attr("href", "http://www.cnblogs.com/tangge”); 4、使用 removeAttr 删除属性。删除的属性在源代码中看不到,这是和清空属性的区别。“查看源文件”只能看服务器上下载下来的那份。$(function () {
$("#btn").click(function () {
$("#link").attr("href", "http://www.baidu.com");
});
$("#btn_move").click(function () {
//获取属性值
//$("#link").attr("href");
//删除属性值
$("#link").removeAttr("href");
});
}
)
BaiDu
案例:图片浏览器
对比 开始的【 DOM版:】
节点遍历
1.next()方法用于获取节点之后的挨着的第一个同辈元素,$(".menuitem").next("div")、nextAll()方法用于获取节点之后的所有同辈元素,$(".menuitem").nextAll("div")
2.prev、prevAll兄弟中之前的元素。
3.siblings()方法用于获取所有同辈元素,$(".menuitem").siblings("li")。siblings、next等所有能传递选择器的地方能够使用的语法都和$()语法一样。
4.end()将匹配的元素列表变为前一次的状态。
//end() 返回上一次包装集被破坏之前的状态
$("#d4").nextAll().css("background-color", "blue").end().css("background-color",
"red");
5.andSelf()加入先前所选的加入当前元素中
6.案例:横向菜单,选中的项高亮显示 $(this).css();$(this).siblings().css()
*
{
margin:0;
padding:0;
}
#menu
{
list-style-type:none;
margin-top:50px;
margin-left:100px;
}
#menu li
{
float:left;
width:100px;
height:30px;
line-height:30px;
background-color:Gray;
text-align:center;
cursor:pointer;
}
$(document).ready(function () {
$("#menu li").click (function () {
$(this).css("background-color", "red").siblings().css("background-color", "Gray");
})
})
首页
播客
相册
关于
7.案例:评分控件。prevAll,this,nextAll
*
{
margin:0;
padding:0;
}
#rating
{
list-style-type:none;
margin:50px 100px;
}
#rating li
{
float:left;
width:20px;
text-align:center;
cursor:pointer;
}
$(function () {
$("#rating li").mouseover(function () {
//alert(1);
$(this).prevAll().andSelf().css("color", "red").end().end().nextAll().css("color", "black");
//分开写(上面用链式编程)
//$(this).prevAll().andSelf().css("color", "red");
//$(this).nextAll().css("color", "black");
})
})
☆
☆
☆
☆
☆