jQuery 文档操作

来源:互联网 发布:linux串口数据互传 编辑:程序博客网 时间:2024/06/04 01:19

定义和用法
text() 方法方法设置或返回被选元素的文本内容。它主要包括三点:
1.设置 2.返回 3.使用函数设置文本内容。

1设置文本内容
当该方法用于设置值时,它会覆盖被选元素的所有内容。
例子:
$(selector).text(content)
参数 content
描述 规定被选元素的新文本内容。注释:特殊字符会被编码。

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $(".btn1").click(function(){    $("p").text("Hello world!");  });});</script></head><body><p>This is a paragraph.</p><p>This is another paragraph.</p><button class="btn1">改变所有 p 元素的文本内容</button></body></html>

这里写图片描述
点击之后结果:
这里写图片描述

2.返回文本内容
当该方法用于返回一个值时,它会返回所有匹配元素的组合的文本内容(会删除 HTML 标记)。
$(selector).text()
例如:

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $(".btn1").click(function(){    alert($("p").text());  });});</script></head><body><p>This is a paragraph.</p><p>This is another paragraph.</p><button class="btn1">获得 p 元素的文本内容</button></body></html>

这里写图片描述
点击之后
这里写图片描述
这样就把想要返回标签里面内容的值返回出来。
3.使用函数设置文本内容
使用函数设置所有被选元素的文本内容。
语法
$(selector).text(function(index,oldcontent))
参数 function(index,oldcontent)
描述 必需。规定返回被选元素的新文本内容的函数。
index - 可选。接受选择器的 index 位置。
html - 可选。接受选择器的当前内容。

例如

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $("button").click(function(){    $("p").text(function(n){    return "这个 p 元素的 index 是:" + n;    });  });});</script></head><body><p>This is a paragraph.</p><p>This is another paragraph.</p><button class="btn1">改变所有 p 元素的文本内容</button></body></html>

这里写图片描述
点击之后返回结果
这里写图片描述

感谢W3C!