JQuery DOM

来源:互联网 发布:java 装饰者模式 io流 编辑:程序博客网 时间:2024/04/28 22:04

3.1内容操作

(1)text():获取或设置文本内容(等价于DOM中的innerText)。

alert($("#p1").text());//捕获

alert($("#p1").text("更改成我"));//内容更改

 

(2)html():获取或设置元素中的所有内容(html的标签。

var content= "<tr>";
content+="<td>JavaScript</td>>";
content+="<td>张三</td>>";
content+="<td>清华大学出版社</td>>";
content+="<tr>";
$("#tblBook").html(content);

 

(3)val():获取或设置表单中的值。

alert($("#txt1").val("请不要输入内容"));

 

(4)attr():获取或设置元素的属性值。

alert($("#txt1").attr("name","第二章"));

3.2元素的添加

(1)append():在元素的结尾添加内容。可以添加多个内容,这些内容可以是通过HTML、JQuery、DOM、创建的。

(2)prepend():在元素的头部添加内容。

(3)after()和before()

两组添加的区别:append()prepend()添加后成为了其子元素。

                 after()和before()添加后成为了其兄弟元素

3.3元素的删除

remove():删除的是被选元素及其子元素

$("#btn1").click(function(){
    $("#div1").remove();
});

 

empty():删除的是被选元素下的子元素

$("#btn2").click(function(){
    $("#div2").empty();
});

 

remove()还有过滤删除的作用,可以删除指定元素,里面的参数就是指定元素的名字。

$("#btn1").click(function(){
    $("p").remove(".p2");
});

这个代码的作用:删除所有p标签中class名为“p2”的元素。

3.4操作CSS类

(1)添加class类:addClass();

(2)删除class类:removeClass();

(3)切换class类:toggleClass()

3.5操作CSS方法

$("p").css("color","green")

()里有两个参数:第一个参数是要设置的属性名,第二个参数是要设置的属性值。

css()也可以设置多个属性,不同属性用”,”隔开,属性名和属性值用”:”隔开,最外层用”{}”括起来。

4导航

4.1祖先

parent():当前元素的父元素

$("#myself").parent().css("backgroundColor","red");

 

parents():所有的祖先元素

$(".myself").parents("[name ='zhang']").css("backgroundColor","red")

 

注意:如果在小括号内传入参数,就可以找到你所指定的那一个祖先元素。

parentsuntil():选中两个指定元素中的祖先元素。

4.2后代

children():当前元素的直接后代

$(".myself").children(".firstSon").css("backgroundColor","red")

 

在括号中传入参数,找到的是指定的直接后代

children.children():直接后代的子元素

$("#myself").children().children().css("backgroundColor","black");

 

find():找到当前元素的所有直接后代

$(".myself").find("div").css("backgroundColor","red")

 

4.3同胞

next():找到弟弟元素

$("#myself").next().css("backgroundColor","yellow");

 

sibling:找到当前元素的所有同胞元素。

$(".myself").siblings().css("backgroundColor","red")

 

nextAll():找到所有的弟弟元素

$(".myself").nextAll().css("backgroundColor","red")

 

prev():找到哥哥元素

$("#myself").prev().css("backgroundColor","blue");

 

nextUntil():找到的是当前元素到指定元素之间的同胞元素。

$(".myself").nextUntil(".p6").css("backgroundColor","red")

 

prevAll():找到当前元素的所有哥哥元素

$(".p6").prevAll().css("backgroundColor","red")

 

原创粉丝点击