一、jQuery DOM 操作

(1)获得内容

//获得text

$("#btn1").click(function(){

alert("Text: " + $("#test").text());
});

//获得html

$("#btn2").click(function(){ 

alert("HTML: " + $("#test").html());

});

//获得val

$("#btn3").click(function(){

alert("值为: " + $("#test").val());

});

//设置内容

$("#btn4").click(function(){

$("#test4").val("text");

});

(2)获取属性

$("button").click(function(){

alert($("#runoob").attr("href"));

});

$("button").click(function(){

$("#runoob").attr({

"href" : "http://www.runoob.com/jquery",

"title" : "jQuery 教程" },

function(){

//回调方法

//todo

});

});

二、添加元素

  • append() - 在被选元素的结尾插入内容
  • prepend() - 在被选元素的开头插入内容
  • after() - 在被选元素之后插入内容
  • before() - 在被选元素之前插入内容

//添加新的文本

function appendText() {

var txt1="<p>文本。</p>"; // 使用 HTML 标签创建文本

var txt2=$("<p></p>").text("文本。"); // 使用 jQuery 创建文本

var txt3=document.createElement("p");

txt3.innerHTML="文本。"; // 使用 DOM 创建文本 text with DOM $("body").append(txt1,txt2,txt3); // 追加新元素

}

 

function afterText() {

var txt1="<b>I </b>"; // 使用 HTML 创建元素

var txt2=$("<i></i>").text("love "); // 使用 jQuery 创建元素

var txt3=document.createElement("big"); // 使用 DOM 创建元素 txt3.innerHTML="jQuery!";

$("img").after(txt1,txt2,txt3); // 在图片后添加文本

}

 

三、删除元素

$("#div1").remove();//删除被选元素及其子元素

$("#div1").empty();//删除被选元素的子元素

$("p").remove(".italic");//删除 class="italic" 的所有 <p> 元素

四、获取并设置 CSS 类

  • addClass() - 向被选元素添加一个或多个类
  • removeClass() - 从被选元素删除一个或多个类
  • toggleClass() - 对被选元素进行添加/删除类的切换操作
  • css() - 设置或返回样式属性

//向不同的元素添加 class 属性

$("button").click(function(){

$("h1,h2,p").addClass("blue important");

$("div").addClass("important");

});

//在不同的元素中删除指定的 class 属性

$("button").click(function(){

$("h1,h2,p").removeClass("blue");

});

//对被选元素进行添加/删除类的切换操作

$("button").click(function(){

$("h1,h2,p").toggleClass("blue");

});

 

//设置css

$("p").css("background-color");

$("p").css("background-color","yellow");

 

css({"propertyname":"value","propertyname":"value",...});

$("p").css({"background-color":"yellow","font-size":"200%"});

 

五、尺寸方法

  • width()
  • height()
  • innerWidth()
  • innerHeight()
  • outerWidth()
  • outerHeight()

//设置width() 和 height()

$("button").click(function(){

var txt=""; txt+="div 的宽度是: " + $("#div1").width() + "</br>";

txt+="div 的高度是: " + $("#div1").height();

$("#div1").html(txt);

});

 

//设置innerWidth() 和 innerHeight() 

$("button").click(function(){

var txt=""; txt+="div 宽度,包含内边距: " + $("#div1").innerWidth() + "</br>"; txt+="div 高度,包含内边距: " + $("#div1").innerHeight(); $("#div1").html(txt); });

 

//设置outerWidth() 和 outerHeight() 

$("button").click(function(){

var txt="";

txt+="div 宽度,包含内边距和边框: " + $("#div1").outerWidth() + "</br>";

txt+="div 高度,包含内边距和边框: " + $("#div1").outerHeight(); $("#div1").html(txt);

});