使用 Toggle() 使用 jQuery 显示 HTML 内容
Using Toggle() to show an HTML content using jQuery
我正在尝试学习一些 jQuery 我需要一些关于这个小程序的帮助,就像你看到的我有一个 header 其中包含一些文本,我需要确保它在使用 Toggle()
.
单击后扩展到它的 HTML 内容
这是我的HTML
<body>
<div class="tog">
<h1 id="hh">
<span> Click me to see my HTML content <span>
<!-- A comment -->
</h1>
</div>
</body>
这是我的 jQuery 代码
<script src="jquery.js"></script>
<script>
$(function ()
{
$(".tog").click(function (){
$('#hh').slideToggle("slow");
$(this).toggleClass("active");
if ($(this).text() == "Click me to see my HTML content ")
$(this).html(h1);
else
$(this).text("Click me to see my HTML content ");
});
</script>
$(this).html(h1);
行在您的情况下无效,它将查找名为 h1
的变量而不是创建 <h1>
标记,html()
函数只需要一个字符串作为输入,因此将您的函数更改为
$(".tog").click(function (){
// you don't need any of the previous lines
console.log($('#hh').html()); //this would show the comments as well
if ($(this).text() == "Click me to see my HTML content ")
$(this).html("<h1 id='hh'><span> Click me to see my HTML content <span><!-- A comment --></h1>");
else
$(this).text("Click me to see my HTML content ");
});
我正在尝试学习一些 jQuery 我需要一些关于这个小程序的帮助,就像你看到的我有一个 header 其中包含一些文本,我需要确保它在使用 Toggle()
.
这是我的HTML
<body>
<div class="tog">
<h1 id="hh">
<span> Click me to see my HTML content <span>
<!-- A comment -->
</h1>
</div>
</body>
这是我的 jQuery 代码
<script src="jquery.js"></script>
<script>
$(function ()
{
$(".tog").click(function (){
$('#hh').slideToggle("slow");
$(this).toggleClass("active");
if ($(this).text() == "Click me to see my HTML content ")
$(this).html(h1);
else
$(this).text("Click me to see my HTML content ");
});
</script>
$(this).html(h1);
行在您的情况下无效,它将查找名为 h1
的变量而不是创建 <h1>
标记,html()
函数只需要一个字符串作为输入,因此将您的函数更改为
$(".tog").click(function (){
// you don't need any of the previous lines
console.log($('#hh').html()); //this would show the comments as well
if ($(this).text() == "Click me to see my HTML content ")
$(this).html("<h1 id='hh'><span> Click me to see my HTML content <span><!-- A comment --></h1>");
else
$(this).text("Click me to see my HTML content ");
});