jQuery 中非常重要的部分,就是操作 DOM 的能力。
获取/设置
获取或设置内容-text()、html()以及 val()
text()-设置或返回所选元素的文本内容
html()-设置或返回所选元素的内容(包括 HTML 标记)
val()-设置或返回表单字段的值
//获取内容 $("#btn1").click(function(){ alert("text:"+$("#test").text()); alert("HTML: " + $("#test").html()); alert("Value: " + $("#test").val()); }) //设置内容 $("#btn1").click(function(){ $("#test1").text("Hello world!"); $("#test2").html("<b>Hello world!</b>"); $("#test3").val("Dolly Duck"); }) //html <p id="test1">这是段落。</p> <p id="test2">这是另一个段落。</p> <p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>
text()、html() 以及 val(),同样拥有回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
$("#btn1").click(function(){ $("#test1").text(function(i,origText){ return "Old text: " + origText + " New text: Hello world! (index: " + i + ")"; }); });
获取或设置属性-attr()
用于获取属性值。
//获取属性 $("button").click(function(){ alert($("#w3s").attr("href")); }); //设置属性 $("button").click(function(){ $("#w3s").attr("href","http://www.w3school.com.cn/jquery"); }); //设置多个属性 $("button").click(function(){ $("#w3s").attr({ "href" : "http://www.w3school.com.cn/jquery", "title" : "W3School jQuery Tutorial" }); }); //html <p><a href="http://www.w3school.com.cn" id="w3s">W3School.com.cn</a></p>
jQuery 方法 attr(),也提供回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
$("button").click(function(){ $("#w3s").attr("href", function(i,origValue){ return origValue + "/jquery"; }); });
添加
添加新的 HTML 内容
append()-在被选元素的结尾插入内容
prepend()-在被选元素的开头插入内容
after()-在被选元素之后插入内容
before()-在被选元素之前插入内容
删除元素/内容
remove()-删除被选元素(及其子元素) 例如:$("#div1").remove();
empty()-从被选元素中删除子元素 例如:$("#div1").empty();
过滤被删除的元素
jQuery remove()方法也可以接受一个参数,允许对被删除元素进行过滤。
例如:$("p").remove(".italic");//删除class="italic" 的所有 <p> 元素
操作 CSS
addClass()-向被选元素添加一个或多个类
removeClass()-从被选元素删除一个或多个类
toggleClass()-对被选元素进行添加/删除类的切换操作
css()-设置或返回样式属性
//CSS样式 .important{ font-weight:bold; font-size:xx-large; } .blue{ color:blue; } //addClass()方法 $("button").click(function(){ $("h1,h2,p").addClass("blue"); $("div").addClass("important"); $("h3").addClass("important blue"); }) //removeClass()方法 $("button").click(function(){ $("h1,h2,p").removeClass("blue"); }) //toggleClass()方法 $("button").click(function(){ $("h1,h2,p").toggleClass("blue"); })
css()方法
返回 css 属性 语法:css("propertyname");
实例:$("p").css("background-color");
设置 css 属性 语法:css("propertyname","value");
实例:$("p").css("background-color","yellow");
设置多个 css 属性
语法:css({"propertyname":"value","propertyname":"value",...});
实例:$("p").css({"background-color":"yellow","font-size":"200%"});
jQuery 尺寸 方法
width()-方法设置或返回元素的宽度(不包括内边距、边框或外边距)。
height()-方法设置或返回元素的高度(不包括内边距、边框或外边距)。
innerWidth()-方法返回元素的宽度(包括内边距)。
innerHeight()-方法返回元素的高度(包括内边距)。
outerWidth()-方法返回元素的宽度(包括内边距和边框)。
outerHeight()-方法返回元素的高度(包括内边距和边框)。
outerWidth(true)-方法返回元素的宽度(包括内边距、边框和外边距)。
outerHeight(true)-方法返回元素的高度(包括内边距、边框和外边距)。
设置元素的宽度和高度可以用 width(value)和 height(value)
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于