我們用以下三個方法來設定內容:
下面的範例示範如何透過 text()、html() 與 val() 設定內容:
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
上述三個方法 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 <b>world!</b> (index: " + i + ")";
});
});