获得内容和属性
$("#test").html(); // 设置或返回所选元素的内容(包括 HTML 标记) $("#test").text(); // 设置或返回所选元素的文本内容 $("#test").val(); // 设置或返回表单字段的值 $("#test").attr("href"); // 用于获取属性值
设置内容和属性
$("#test2").html("<b>Hello world!</b>"); $("#test1").text("Hello world!"); $("#test3").val("Dolly Duck"); $("#w3s").attr("href","http://www.w3school.com.cn/jquery");
回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
$("#test1").text(function(i,addTest){ return "hello" + str! //return (index: " + i + ")"; });
回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
$("#w3s").attr("href", function(i,origValue){ return origValue + "/jquery"; });
添加元素
$("p").append("Some appended text."); // 在被选元素的结尾插入内容 $("p").append(txt1,txt2,txt3); $("p").prepend("Some prepended text."); // 在被选元素的开头插入内容 $("img").after("Some text after"); // 在被选元素之后插入内容 $("img").after(txt1,txt2,txt3); $("img").before("Some text before"); // 在被选元素之前插入内容
删除元素
$("#div1").remove(); // 方法删除被选元素及其子元素。 $("#div1").empty(); // 方法删除被选元素的子元素。 $("p").remove(".italic"); // 删除 class="italic" 的所有 <p> 元素(该参数可以是任何 jQuery 选择器的语法)
获取并设置 CSS 类
$("h1,h2,p").addClass("blue"); $("h1,h2,p").removeClass("blue"); $("h1,h2,p").toggleClass("blue");
获取并设置 css() 方法
$("p").css("background-color"); $("p").css("background-color","yellow"); $("p").css({"background-color":"yellow","font-size":"200%"});
设置或返回 - 尺寸
$("#div1").width(); // 元素的宽度(不包括内边距、边框或外边距) $("#div1").height(); // 元素的高度(不包括内边距、边框或外边距) $("#div1").innerWidth(); // 返回元素的宽度(包括内边距) $("#div1").innerHeight(); // 返回元素的高度(包括内边距) $("#div1").outerWidth(); // 返回元素的宽度(包括内边距和边框) $("#div1").outerHeight(); // 返回元素的高度(包括内边距和边框)