本文概述
jQuery html()方法用于更改所选元素的全部内容。它将选定的元素内容替换为新的内容。
注意:这是一个非常有用的功能, 但由于其API文档而在有限的范围内起作用。 jQuery html函数的API文档包含三个方法签名。
第一个方法签名没有参数, 因此它仅返回该元素内的HTML。其余两个签名使用一个参数:即字符串或返回字符串的函数。
句法:
$(selector).html()
它用于返回内容。
$(selector).html(content)
用于设置内容。
$(selector).html(function (index, currentcontent))
通过调用函数来设置内容。
jQuery html()方法用于设置内容或返回所选元素的内容。
- 设置内容:使用此方法设置内容时, 它将覆盖所有匹配元素的内容。
- 返回内容:使用此方法返回内容时, 它将返回第一个匹配元素的内容。
text()方法用于设置或仅返回所选元素的文本内容。
jQuery html()方法的参数
参数 | 描述 |
---|---|
Content | 它是必不可少的参数。用于指定所选元素的新内容。它还可以包含HTML标记。 |
Function (index, currentcontent) | 它是一个可选参数。它指定一个函数, 该函数返回所选元素的新内容。索引:显示元素在集合中的索引位置。 Currentcontent:显示所选元素的当前HTML内容。 |
jQuery html()方法的示例
让我们以一个示例来演示jQuery html()方法。它正在改变所有p元素的内容。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").html("Hello <b>srcmini02.com</b>");
});
});
</script>
</head>
<body>
<button>Click here to change the content of all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
立即测试
输出:
单击此处更改所有p元素的内容
这是一段。
这是另一段。
jQuery html()示例2
让我们看一下返回HTML内容的jQuery html()方法的另一个示例。它仅返回第一段的内容。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("p").html());
});
});
</script>
</head>
<body>
<button>Return the content of p element</button>
<p>This is first <b>paragraph</b>.</p>
<p>This is another <b>paragraph</b>.</p>
</body>
</html>
立即测试
输出:
返回p元素的内容
这是第一段。
这是另一段。
jQuery html()示例3
让我们看一下将HTML转换为文本的jQuery html()方法的另一个示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>html demo</title>
<style>
p {
margin: 8px;
font-size: 20px;
color: blue;
cursor: pointer;
}
b {
text-decoration: underline;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>
<b>Click</b> here to change the <span id="tag">html</span> to text
</p>
<script>
$( "p" ).click(function() {
var htmlString = $( this ).html();
$( this ).text( htmlString );
});
</script>
</body>
</html>
立即测试
输出:
单击此处将html更改为文本
评论前必须登录!
注册