jQuery獲取HTML元素內容和屬性。
DOM-Document Object Model文檔對象模型
獲得內容-text()、html()及val()
text()-設置或返回所選元素的文本內容
html()-設置或返回所選元素的內容(包括HTML標記)
val()-設置或返回表單字段的值
$(document).ready(function(){
$("#btn1").click(function(){
alert("Text:" + $("#test").text());
});
$("#btn2").click(function(){
alert("Html"+$("#test").html());
});
$("#btn2").click(function(){
alert("value"+$("#test").val());
});
});
獲取屬性-attr()
如何獲得鏈接中 href 屬性的值:
$("button").click(function(){
alert($("#w3s").attr("href"));
});
設置內容
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
回調函數
$("#btn1").click(function(){
$("#test1").text(function(i,origText){
return "Old text: " + origText + " New text: Hello world!
(index: " + i + ")";
});
});
$("#btn2").click(function(){
$("#test2").html(function(i,origText){
return "Old html: " + origText + " New html: Hello <b>world!</b>
(index: " + i + ")";
});
});
設置屬性attr()
$("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"
});
});
attr的回調函數
$("button").click(function(){
$("#w3s").attr("href", function(i,origValue){
return origValue + "/jquery";
});
});
jQuery添加元素
append() - 在被選元素的結尾插入內容
$("p").append("Some appended text.");
prepend() - 在被選元素的開頭插入內容
$("p").prepend("Some prepended text.");
通過append和prepend方法能夠通過參數接收無限數量的新元素。
function appendText()
{
var txt1="<p>Text.</p>"; // Create element with HTML
var txt2=$("<p></p>").text("Text."); // Create with jQuery
var txt3=document.createElement("p"); // Create with DOM
txt3.innerHTML="Text.";
$("p").append(txt1,txt2,txt3); // Append the new elements
}
after() - 在被選元素之後插入內容
before() - 在被選元素之前插入內容
$("img").after("Some text after");
$("img").before("Some text before");
function afterText()
{
var txt1="<b>I </b>"; // Create element with HTML
var txt2=$("<i></i>").text("love "); // Create with jQuery
var txt3=document.createElement("big"); // Create with DOM
txt3.innerHTML="jQuery!";
$("img").after(txt1,txt2,txt3); // Insert new elements after img
}
jQuery-刪除元素
remove()-刪除被選元素(及其子元素)
remove()也可以接受一個參數,對被刪的元素進行過濾。
$(“p”).remove(“.italic”);即刪除包含class=”italic”的元素
empty()-從被選元素中刪除子元素。
jQuery-獲取並設置CSS類
addClass() - 向被選元素添加一個或多個類
removeClass() - 從被選元素刪除一個或多個類
toggleClass() - 對被選元素進行添加/刪除類的切換操作
css() - 設置或返回樣式屬性
.important
{
font-weight:bold;
font-size:xx-large;
}
.blue
{
color:blue;
}
$("button").click(function(){
$("#div1").addClass("important blue");
});