zoukankan      html  css  js  c++  java
  • jquery

    一般我们会遇到给某个元素添加或更改原有的文字:

    1. 设置/获取内容 - text()、html() 以及 val()

    • 设置内容常用的三个方法:
      text() - 设置或返回所选元素的文本内容
      html() - 设置或返回所选元素的内容(包括 HTML 标记)
      val() - 设置或返回表单字段的值
      eg: 通过 text()、html() 以及 val() 方法来设置/获取内容:
      $("#btn1").click(function(){
        $("#test1").text("Hello world!");   //设置
        //获取:$("#test1").text();
      });
      $("#btn2").click(function(){
        $("#test2").html("<b>Hello world!</b>");   //设置
        //获取: $("#test2").html();
      });
      $("#btn3").click(function(){
        $("#test3").val("Dolly Duck");   //设置
        //获取:$("#test3").val();
      });
    • text()、html() 以及 val() 的回调函数
      
      上面的三个 jQuery 方法:text()、html() 以及 val(),同样拥有回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
      eg: 带有回调函数的 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 + ")";
        });
      });

    2. 设置/获取属性 - attr()

    • jQuery attr() 方法也用于设置改变/获取属性值。
      eg: 改变(设置)链接中 href 属性的值:
      
      $("button").click(function(){
        $("#w3s").attr("href","http://www.w3school.com.cn/jquery");  //设置改变 
      //获取:$("#w3s").attr("href"); });
    • attr() 方法也允许您同时设置多个属性。
      eg: 同时设置 href 和 title 属性:
      
      $("button").click(function(){
        $("#w3s").attr({
          "href" : "http://www.w3school.com.cn/jquery",
          "title" : "W3School jQuery Tutorial"
        });
      });
    • attr() 的回调函数
      jQuery 方法 attr(),也提供回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
      
      eg: 带有回调函数的 attr() 方法:
      $("button").click(function(){
        $("#w3s").attr("href", function(i,origValue){
          return origValue + "/jquery";
        });
      });
  • 相关阅读:
    基于发布/订阅模型的应用程序的主循环设计
    C++使用继承时子对象的内存布局
    安装 CentOS 后的系统配置及软件安装备忘
    环形无锁队列
    并发编程基础
    线程池实现
    Git远程操作
    Unix权限管理
    jquery中,某些写法后来更新导致版本不支持的替代方法
    js相关
  • 原文地址:https://www.cnblogs.com/ostrich-sunshine/p/8376442.html
Copyright © 2011-2022 走看看