• 技术文章 >web前端 >前端问答

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

    长期闲置长期闲置2022-05-10 11:44:28原创242

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

    本教程操作环境: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>

    输出结果:

    01.png

    点击按钮后:

    02.png

    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>

    输出结果:

    03.png

    点击按钮后:

    04.png

    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>

    输出结果:

    05.png

    点击按钮后:

    06.png

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

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

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:jquery
    上一篇:jquery怎么从dom删除所有匹配的元素 下一篇:jquery中each是什么意思
    千万级数据并发解决方案

    相关文章推荐

    • jquery中怎么让th元素隐藏• jquery有几个基本选择器• jquery怎么用CSS()设置鼠标禁止样式• jquery中有map方法吗• jquery怎么用click改变id
    1/1

    PHP中文网