1. 捕获
<p id="text">This is my webpage<a>This is a tag</a></p>
<button id="btn1">click</button>
<p><input type="text" id="it" value="jikexueyuan"></p>
<p><a href="http://www.baidu.com" id="aid"></a></p>
<button id="btn2">click</button>
JS CODE:
$(document).ready(function(){
$("#btn1").click(function(){
alert("text:"+$("#text").text())
});
// $("#btn1").click(function(){
// alert("text:"+$("#text").html()); //html() can get the tag.
// });
$("#btn1").click(function(){
alert("text:"+$("#it").val());
});
$("#btn2").click(function(){
alert("text:"+$("#aid").attr("href"));
});
});
2. 设置
<p id="p1">Hello world</p>
<p id="p2">I love you</p>
<input type="text" id="i3" value="hello world"><br>
<a id="aid" href="http://www.baidu.com">baidu</a><br>
<p id="p5">hello world</p>
<button id="btn1">button 1</button>
<button id="btn2">button 2</button>
<button id="btn3">button 3</button>
<button id="btn4">button 4</button>
<button id="btn5">button 5</button>
JS CODE:
$(document).ready(function(){
$("#btn1").click(function(){
$("#p1").text("jikexueyuan");
});
$("#btn2").click(function(){
$("#p2").html("<a href=‘http://www.baidu.com‘>baidu</a>");
});
$("#btn3").click(function(){
$("#i3").val("jikexueyuan");
});
$("#btn4").click(function(){
$("#aid").attr({
"href":"http://www.apple.com",
"title": "foo"
});
});
$("#btn5").click(function(){
$("#p5").text(function(i,ot){
return "old:"+ot+" new:This is new content"+(i);
});
});
});
3. 元素添加
<p id="p1">hello world</p>
<p id="p2">hello world</p>
<button id="btn1">button 1</button>
<button id="btn2">button 2</button>
<button onclick="appendText()">button3</button>
$(document).ready(function(){
$("#btn1").click(function(){
//$("#p1").append(" This is my webpage add content");
$("#p1").prepend("This is my webpage add content ");
});
$("#btn2").click(function(){
//$("#p2").before("hello");
$("#p2").after("hello");
});
});
function appendText(){
//html jquery js-dom
var text1 = "<p>iwen</p>";
var text2 = $("<p></p>").text("ime");
var text3 = document.createElement("p");
text3.innerHTML = "foo";
$("body").append(text1,text2,text3);
};
4. 删除元素
<div id="div" style="height: 200px; width: 200px; border:1px solid black;">
hello
<p>hello world</p>
<p>hello</p>
</div>
<button id="btn1">delete</button>
//remove empty
$(document).ready(function(){
$("#btn1").click(function(){
$("#div").remove();
//$("#div").empty();
});
});