美元符号 ($) 在 jQuery 中是什么意思?

$ 符号不过是 jQuery() 函数的标识符。 

我们不编写 jQuery,而是编写 $ ,它与 jQuery() 函数相同。带有选择器的 $ 指定它是一个 jQuery 选择器。它被赋予一个较短的标识符 $ 只是为了减少编写较大语法的时间。它包含 jQuery 对象使用的所有函数,例如animate()hide()show()css()等等。此外,在内存方面,$ 比 jQuery 更好,因为 $ 占用一个字节,而 jQuery 占用 6 个字节,它们具有相同的功能。 

句法:

$('selector').action();

示例 1:一个简单的插图来说明 jQuery 和 $ 具有相同的功能。

<!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">

        <!-- Including jQuery -->
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"
                integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
                crossorigin="anonymous">
        </script>
    </head>

    <body>
        <script>
            console.log($ === jQuery)
        </script>
    </body>

</html>

输出:

true

注意: $('p') 和 jQuery('p') 具有相同的含义,并且它们返回相同的对象。

示例 2:

<!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">

        <!-- Including jQuery -->
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"
                integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
                crossorigin="anonymous">
        </script>
    </head>

    <body>
        <p> This is a paragraph</p>
        <script>
            var p = $('p').text();
            var x = jQuery('p').text()
            console.log(p);
            console.log(x);
        </script>
    </body>
</html>

输出:

 

我们甚至可以使用 jQuery noConflict()函数更改 $,因为当我们使用其他可能具有不同含义的技术时,可能会有机会,在这种情况下,我们可以使用noConflict()方法为 jQuery 自定义标识符。

句法:

var new_identifier = jQuery.noConflict();

示例 3:

<!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">

        <!-- Including jQuery -->
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"
                integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
                crossorigin="anonymous">
        </script>
    </head>

    <body>

        <p> This is a paragraph</p>

        <script>
            var dollar = jQuery.noConflict();

            // We can use dollar instead of $ by
            // using jQuery noConflict() method
            var x = dollar('p').text()
            console.log(x);
        </script>
    </body>

</html>

输出:

This is a paragraph

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值