您的位置:首页 > Web前端 > JQuery

jQuery-DOM

2016-05-31 17:01 302 查看
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");
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: