美文网首页
jQuery - 设置内容和属性

jQuery - 设置内容和属性

作者: moralok | 来源:发表于2017-09-16 17:01 被阅读0次

2017-09-16
摘抄自W3school-jQuery - 设置内容和属性
希望帮助自己系统地打好基础,也能在做笔记的同时添加一些自己额外的收获。

设置内容 - text()、html() 以及 val()

我们将使用前一章中的三个相同的方法来设置内容:

  • text() - 设置或返回所选元素的文本内容
  • html() - 设置或返回所选元素的内容(包括 HTML 标记)
  • val() - 设置或返回表单字段的值
    下面的例子演示如何通过 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() 的回调函数

上面的三个 jQuery 方法: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 + ")";
  });
});

设置属性 - attr()

jQuery attr() 方法也用于设置/改变属性值。
下面的例子演示如何改变(设置)链接中 href 属性的值:

$("button").click(function(){
  $("#w3s").attr("href","http://www.w3school.com.cn/jquery");
});

attr() 方法也允许您同时设置多个属性。
下面的例子演示如何同时设置 href 和 title 属性:

$("button").click(function(){
  $("#w3s").attr({
    "href" : "http://www.w3school.com.cn/jquery",
    "title" : "W3School jQuery Tutorial"
  });
});

attr() 的回调函数

jQuery 方法 attr(),也提供回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
下面的例子演示带有回调函数的 attr() 方法:

$("button").click(function(){
  $("#w3s").attr("href", function(i,origValue){
    return origValue + "/jquery";
  });
});

相关文章

  • jQuery - 设置内容和属性

    2017-09-16摘抄自W3school-jQuery - 设置内容和属性希望帮助自己系统地打好基础,也能在做笔...

  • jQuery 操作form表单

    jQuery 操作form表单 1、属性操作 设置属性 获取属性 移除属性 2、值和内容 val ( ) text...

  • web进阶之二十六:JQuery的一些效果实现

    jquery属性操作 html() 取出或设置html内容 text() 取出或设置text内容 attr() 取...

  • 获取、检查、设置、移除属性节点

    setAttribute()设置属性;removeAttribute()移除属性; 对比在jQuery中获取和设置...

  • jQuery | 获取及设置内容和属性

    获取 什么是DOM?DOM = Document Object Model(文档对象模型),用来定义访问 HTML...

  • 2019-06-17

    jq基础知识 属性操作 jquery属性操作1、html() 取出或设置html内容 2、text() 取出或设置...

  • 15

    jquery属性操作 1、html() 取出或设置html内容 // 取出html内容 var $htm = $(...

  • 2019-06-14

    jquery属性操作 1、html() 取出或设置html内容 // 取出html内容 var $htm = $(...

  • jQuery基本函数整理

    来源于《15天学会jQuery编程与实战》 jQuery操作HTML 获取内容 获取元素的属性 设置元素的属性 页...

  • 15、获取和设置表单内容

    val():获取和设置表单内容 原生js是通过value属性来获取或者设置表单元素值 jQuery是通过 var(...

网友评论

      本文标题:jQuery - 设置内容和属性

      本文链接:https://www.haomeiwen.com/subject/smfusxtx.html