jQuery-DOM

来源:互联网 发布:人工智能演讲稿 编辑:程序博客网 时间:2024/03/29 01:45

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 jQueryvar txt3=document.createElement("p");  // Create with DOMtxt3.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 jQueryvar txt3=document.createElement("big");  // Create with DOMtxt3.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");}); 
0 0
原创粉丝点击