jquery中text()、val()和html()的区别是什么


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

jquery中text()、val()和html()的区别:text()用于html元素文本内容的存取;html()不但可以用于html元素文本内容的存取,还可以用于html内容的存取;val()仅用于input元素内容的存取。

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

共同点:text(),html() ,val()三个方法用于html元素的存值和取值。

区别:

  • text()用于html元素文本内容的存取
  • html()不但可以用于html元素文本内容的存取,还可以用于html内容的存取
  • val()用于input元素内容的存取

text()定义和用法

text() 方法方法设置或返回被选元素的文本内容,如果有子标签,则把子标签内的文本一起返回,相当于js的innerText

代码如下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <script src="./js/jquery-1.12.4.js"></script>

    <title>Document</title>

</head>

<body>

    <p id="p1">p有文本内容</p>

    <p id="p2">

        p2内的文本

        <span>span内有文本内容</span>

    </p>

    <input type="text" id="input1" value="这是一个input标签">

    <input type="text" name="" id="input2" placeholder="能成功获取">

    <button id="button1" value="这是一个button标签"></button>

    

 <script>

        console.log($("#p1").text());

        console.log($("#p2").text());

        console.log($("#p2 span").text()) ;

        console.log($("#input1").text());

        console.log($("#input2").text());

        console.log($("#button1").text());

 </script>

 

</body>

</html>

console打印的结果

可以看出text()只输出标签内的文本内容,和js的innerText方法一样

html()定义和用法

html() 方法返回或设置被选元素的内容 (inner HTML),包括标签。如果有子标签,则把子标签本身和子标签内的文本一起返回

相当于js的innerHTML

如果该方法未设置参数,则返回被选元素的当前内容。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<body>

    <p id="p1">p有文本内容</p>

    <p id="p2">

        p2内的文本

        <span>span内有文本内容</span>

    </p>

    <input type="text" id="input1" value="这是一个input标签">

    <input type="text" name="" id="input2" placeholder="能成功获取">

    <button id="button1" value="这是一个button标签"></button>

    <script>

        console.log($("#p1").html());

        console.log($("#p2").html());

        console.log($("#p2 span").html());

        console.log($("#input1").html());

        console.log($("#input2").html());

        console.log($("#button1").html());

    </script>

</body>

通过console的打印的结果

阅读剩余部分

相关阅读 >>

如何使用jQuery对属性进行获取、设置和删除

jQuery中ajax提交数据乱码怎么办

jQuery选择器通过class名获取id实例分享

jQuery的$是什么意思

jQuery css怎么设置高度

jQuery是干嘛的

jQuery选择器是什么

jQuery如何判断是否空对象

jQuery怎么判断值为空

介绍js的四种类型检测方法及根据jQuery写的工具方法

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




打赏

取消

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

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

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

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

评论

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