jquery給dom元素賦值的方法

設置內容 - text()、html() 以及 val() 咱們將使用前一章中的三個相同的方法來設置內容: text() - 設置或返回所選元素的文本內容 html() - 設置或返回所選元素的內容(包括 HTML 標記) val() - 設置或返回表單字段的值 下面的例子演示如何經過 text()、html() 以及 val() 方法來設置內容: $("#btn1").click(function(){   $("#test1").text("Hello world!"); }); $("#btn2").click(function(){   $("#test2").html("Hello world!"); }); $("#btn3").click(function(){   $("#test3").val("Dolly Duck"); });
text()、html() 以及 val() 的回調函數 上面的三個 jQuery 方法:text()、html() 以及 val(),一樣擁有回調函數。回調函數由兩個參數:被選元素列表中當前元素的下標,以及原始(舊的)值。而後以函數新值返回您但願使用的字符串。 下面的例子演示帶有回調函數的 text() 和 html(): $("#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 world!     (index: " + i + ")";   }); });
設置屬性 - attr() jQuery attr() 方法也用於設置/改變屬性值。 下面的例子演示如何改變(設置)連接中 href 屬性的值: 實例 $("button").click(function(){   $("#w3s").attr("href",http://www.hello-code.com); }); attr() 方法也容許您同時設置多個屬性。 下面的例子演示如何同時設置 href 和 title 屬性: 實例 $("button").click(function(){   $("#w3s").attr({     "href" : http://www.hello-code.com,     "title" : "編程中國社區"   }); }); attr() 的回調函數 jQuery 方法 attr(),也提供回調函數。回調函數由兩個參數:被選元素列表中當前元素的下標,以及原始(舊的)值。而後以函數新值返回您但願使用的字符串。 下面的例子演示帶有回調函數的 attr() 方法: $("button").click(function(){   $("#w3s").attr("href", function(i,origValue){     return origValue + "/jquery";   }); }); 完整實例
<!DOCTYPE html> <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script> //回調函數 $(document).ready(function(){   $("#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 world! (index: " + i + ")";     });   });
}); </script>
<script> //賦值 $(document).ready(function(){   $("#btn1").click(function(){     $("#test1").text("Hello world!");   });   $("#btn2").click(function(){     $("#test2").html("<b>Hello world!</b>");   });   $("#btn3").click(function(){     $("#test3").val("Dolly Duck");   }); }); </script> </head>
<body> <p id="test1">這是粗體文本。</p> <p id="test2">這是另外一段粗體文本。</p> <button id="btn1">顯示舊/新文本</button> <button id="btn2">顯示舊/新 HTML</button> </body> </html>php

轉載於猿2048:☞《jquery給dom元素賦值的方法》html

相關文章
相關標籤/搜索