上篇介绍HTML Get,jQuery其实使用上面同样的三个方法来赋值。

  • text() – 设置或取得指定元素的文本内容。

  • html() – 设置或取得指定元素的内容(包括HTML标记)

  • val() – 设置或取得表单某个输入域的值。

比如下面代码就是使用上面三种方法给HTML元素或Form赋值



  1. $("#btn1").click(function(){  

  2.   $("#test1").text("Hello world!");  

  3. });  

  4. $("#btn2").click(function(){  

  5.   $("#test2").html("<b>Hello world!</b>");  

  6. });  

  7. $("#btn3").click(function(){  

  8.   $("#test3").val("Dolly Duck");  

  9. });  

  10.  



用于text(),html()和val()的回调函数

text(),html()和val()方法可以和一个回调函数配合使用,这个回调函数具有两个参数,一个是选择中元素的序号,第二个为当前值(旧值),然后你可以通过回调函数的返回值做为元素的新值。
例如:


  1. <!DOCTYPE html>  

  2. <html>  

  3. <head>  

  4.    <meta charset="utf-8">  

  5.    <title>JQuery Demo</title>  

  6.    <script src="scripts/jquery-1.9.1.js"></script>  

  7.    <script>  

  8.        $(document).ready(function () {  

  9.            $("#btn1").click(function () {  

  10.                $("#test1").text(function (i, origText) {  

  11.                    return "Old text: " + origText  

  12.                        + " New text: Hello world! (index: " + i + ")";  

  13.                });  

  14.            });  

  15.  

  16.            $("#btn2").click(function () {  

  17.                $("#test2").html(function (i, origText) {  

  18.                    return "Old html: " + origText  

  19.                        + " New html: Hello <b>world!</b> (index: " + i + ")";  

  20.                });  

  21.            });  

  22.  

  23.        });  

  24.    </script>  

  25. </head>  

  26.  

  27. <body>  

  28.    <p id="test1">This is a <b>bold</b> paragraph.</p>  

  29.    <p id="test2">This is another <b>bold</b> paragraph.</p>  

  30.    <button id="btn1">Show Old/New Text</button>  

  31.    <button id="btn2">Show Old/New HTML</button>  

  32. </body>  

  33. </html>  

20130309001
同样为元素的属性赋值也使用attr()方法,例如:



  1. $("button").click(function(){  

  2.   $("#guidebee").attr({  

  3.     "href" : "http://www.imobilebbs.com",  

  4.     "title" : "imobilebbs jQuery Tutorial"  

  5.   });  

  6. });