val()、text()、html()、attr()详解

设置内容 - text()、html() 以及 val()
  • text() - 设置或返回所选元素的文本内容
  • html() - 设置或返回所选元素的内容(包括 HTML 标记)
  • val() - 设置或返回表单字段的值
  • <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
    </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("RUNOOB");
      });
    });
    </script>
    </head>
    
    <body>
    <p id="test1">这是一个段落。</p>
    <p id="test2">这是另外一个段落。</p>
    <p>输入框: <input type="text" id="test3" value="菜鸟教程"></p>
    <button id="btn1">设置文本</button>
    <button id="btn2">设置 HTML</button>
    <button id="btn3">设置值</button>
    </body>
    </html>

     

text()、html() 以及 val() 的回调函数
  • text()、html() 以及 val(),同样拥有回调函数。回调函数有两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
  • 
    $("#btn1").click(function(){
        $("#test1").text(function(i,origText){
            return "旧文本: " + origText + " 新文本: Hello world! (index: " + i + ")"; 
        });
    });
     
    $("#btn2").click(function(){
        $("#test2").html(function(i,origText){
            return "旧 html: " + origText + " 新 html: Hello <b>world!</b> (index: " + i + ")"; 
        });
    });
    

     

设置属性 - attr()
  • jQuery attr() 方法也用于设置/改变属性值。
  • <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("#runoob").attr({
          "href" : "http://www.runoob.com/jquery",
          "title" : "jQuery 教程"
        });
    	// 通过修改的 title 值来修改链接名称
    	title =  $("#runoob").attr('title');
    	$("#runoob").html(title);
      });
    });
    </script>
    </head>
    
    <body>
    <p><a href="//www.runoob.com" id="runoob">菜鸟教程</a></p>
    <button>修改 href 和 title</button>
    <p>点击按钮修改后,可以查看 href 和 title 是否变化。</p>
    </body>
    </html>

     

转载于:https://my.oschina.net/u/4159909/blog/3072806

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值