jquery中html方法实现了哪些功能

lxf2023-03-10 20:08:01

功能:1、返回元素内容,语法“元素对象.html()”;2、设置元素内容,语法“元素对象.html(元素的新内容)”;3、使用函数来设置元素的内容,语法“元素对象.html(function(选择器的index位置,选择器的当前内容))”。

jquery中html方法实现了哪些功能

本教程操作环境:windows10系统、jquery3.2.1版本、Dell G3电脑。

jquery中html方法实现了哪些功能

1、返回元素内容

当使用该方法返回一个值时,它会返回第一个匹配元素的内容。

语法

$(selector).html()

示例如下:

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

输出结果:

jquery中html方法实现了哪些功能

点击按钮后:

jquery中html方法实现了哪些功能

2、设置元素内容

当使用该方法设置一个值时,它会覆盖所有匹配元素的内容。

语法

$(selector).html(content)

content 可选。规定被选元素的新内容。该参数可包含 HTML 标签。

示例如下:

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

输出结果:

jquery中html方法实现了哪些功能

点击按钮后:

jquery中html方法实现了哪些功能

3、使用函数来设置元素内容

使用函数来设置所有匹配元素的内容。

语法

$(selector).html(function(index,oldcontent))

参数 描述

function(index,oldcontent)

规定一个返回被选元素的新内容的函数。

index - 可选。接收选择器的 index 位置。

oldcontent - 可选。接收选择器的当前内容。

示例如下:

<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").html(function(n){
    return "这个 p 元素的 index 是:" + n;
    });
  });
});
</script>
</head>
<body>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<button>改变 p 元素的内容</button>
</body>

输出结果:

jquery中html方法实现了哪些功能

点击按钮后:

jquery中html方法实现了哪些功能

相关视频教程推荐:jQuery视频教程

以上就是jquery中html方法实现了哪些功能的详细内容,更多请关注AdminJS其它相关文章!