jQuery html()方法有什么用


本文摘自PHP中文网,作者青灯夜游,侵删。

html()方法用于返回或设置被选元素的内容:1、如果未设置参数,则返回被选元素的当前内容,语法“$(selector).html()”;2、如果设置参数,则会覆盖所有匹配元素的内容,语法“$(selector).html(内容值)”。

本教程操作环境:windows7系统、jquery1.10.2版本、Dell G3电脑。

jQuery html()方法

html() 方法返回或设置被选元素的内容 (inner HTML)。

  • 返回元素内容

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

语法

1

$(selector).html()

示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<!DOCTYPE html>

<html>

 

    <head>

        <meta charset="utf-8">

        <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">

        </script>

        <script>

            $(document).ready(function() {

                $("button").click(function() {

                    alert($("p").html());

                });

            });

        </script>

    </head>

 

    <body>

        <p>这是一个 <b>段落</b>。</p>

        <button>返回P标签的内容</button>

 

    </body>

 

</html>

1.png

  • 设置元素内容

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

语法

1

$(selector).html(content)

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

示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<!DOCTYPE html>

<html>

 

    <head>

        <meta charset="utf-8">

        <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">

        </script>

        <script>

            $(document).ready(function() {

                $("button").click(function() {

                    $("p").html("Hello <b>world!</b>");

                });

            });

        </script>

    </head>

 

    <body>

 

        <p>这是一个段落。</p>

        <p>这是另一个段落。</p>

        <button>修改所有P元素的内容</button>

    </body>

 

</html>

1.gif

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

以上就是jQuery html()方法有什么用的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

jQuery版本几适应ie8

jQuery三大版本之间有什么区别?

jQuery如何添加节点?

jQuery的ajax()函数传值中文乱码怎么办

jQuery中的webix是什么

jQuery为什么不支持live

jQuery的选择器有几种

jQuery 如何判断是否有div

jQuery中$符号的作用是什么?

jQuery怎样判断是否是字符串

更多相关阅读请进入《jQuery》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...