text()方法设置内容时,会覆盖所有匹配元素的内容;返回的内容用于返回所有匹配元素的文本内容。
语法:
返回文本:
$(selector).text()
设置文本:
$(selector).text(content)
使用函数设置文本:
$(selector).text(function(index, currentcontent))
参数值:
1、content:用于设置元素的新文本内容。
2、Function(index, currentcontent):用于指定将返回所选元素的新文本内容的函数。
● index:返回元素的索引位置。
● currentcontent:返回元素的当前内容。
示例1:向元素添加文本内容
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="text-align: center;">
<h3>单击,向元素添加文本内容</h3>
<button onclick="function()">点击这里</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("p").text("Jquery_text_method");
});
});
</script>
<p>Hello</p>
<p>Jquery</p>
</body>
</html>示例2:返回文本
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="text-align: center;">
<h3>单击,返回文本</h3>
<button onclick="function()">点击这里</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
alert($("p").text());
});
});
</script>
<p>Hello</p>
<p>Jquery</p>
</body>
</html>示例3:使用函数设置文本
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="text-align: center;">
<h3>使用函数设置文本</h3>
<button onclick="function()">点击这里</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("p").text(function(n) {
return "元素索引号: " + n;
});
});
});
</script>
<p>Hello</p>
<p>Jquery</p>
</body>
</html> 





网友评论文明上网理性发言 已有0人参与
发表评论: