jQuery系列——设置

103 阅读1分钟

​​​​​​​​本文已参与「新人创作礼」活动,一起开启掘金创作之路。

设置内容 - text()、html() 以及 val()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery 设置</title>
    <style>
        p{
            cursor: pointer;
        }
        div{
            cursor: pointer;
        }
        input{
            cursor: pointer;
        }
    </style>
</head>
<body>
    <p>一个p标签</p>
    <div>一个div盒子</div>
    <br>
    <input type="text" name="" id="" value="1"> 点击文本框时将改变的值
    <br>
    <a href="#" title="这是第一个页面">点击跳转第二个页面</a>
    <script src="../jquery-3.6.0.js"></script>
    <script>
        $(document).ready(function(){
            $('p').click(function(){
                $('p').text('变成了一个p');
            });
            $('div').click(function(){
                $('div').html('<b>变成了一个加粗的div</b>')
            });
            $('input').click(function(){
                $('input').val('值变成了2');
            });
        });
    </script>
</body>
</html>

设置内容 - text()、html():

效果如图:

 区别在于html()可以添加标签而text()只能更换文本

设置val()

如图:

 设置attr()属性

可以设置多个属性值

//        html

  <a href="#" title="这是第一个页面">点击跳转第二个页面

//        jQuery

 // 设置属性 attr()

            $('a').click(function(){

                // $('a').attr('href','hao.360.com');                //设置单个属性

                $('a').attr({                                                                //设置多个属性

                    "href":"index.html",

                    "title":"这是第二个网页"

                });

            });

效果如图: