1. text() - 设置或返回所选元素的文本内容
  2. html() - 设置或返回所选元素的内容(包括 HTML 标记)
  3. val() - 设置或返回表单字段的值
  4. atrr() -返回被选元素的属性值

s.gif

  1. <p id="test1">这是段落。</p>
  2. <p id="test2">这是另一个段落。</p>
  3. <p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>
  4. <button id="btn1">设置文本</button>
  5. <button id="btn2">设置 HTML</button>
  6. <button id="btn3">设置值</button>
  7. <script>
  8. $(document).ready(function(){
  9. $("#btn1").click(function(){
  10. $("#test1").text("hello world");
  11. });
  12. $('#btn2').click(function(){
  13. $("#test2").html("<i>hello world</i>");
  14. });
  15. $('#btn3').click(function(){
  16. $("#test3").val("Dolly Duck");
  17. });
  18. });
  19. </script>

text()、html() 以及 val() 的回调函数

  1. $("#btn1").click(function(){
  2. $("#test1").text(function(i,origText){
  3. return "Old text: " + origText + " New text: Hello world!
  4. (index: " + i + ")";
  5. });
  6. });
  7. $("#btn2").click(function(){
  8. $("#test2").html(function(i,origText){
  9. return "Old html: " + origText + " New html: Hello <b>world!</b>
  10. (index: " + i + ")";
  11. });
  12. });


atrr()

  1. 改变图像的 width 属性:
  2. $("button").click(function(){
  3. $("img").attr("width","180");
  4. });