jQuery 语法 登录

jQuery 语法

通过 jQuery,您可以选取(查询,query) HTML 元素,并对它们执行"操作"(actions)。


jQuery 语法

在jQuery 程序中,不管是页面元素的选择,还是内置的功能函数,都是以美元符号“$”来起始的,而这个“$”就是jQuery当中最重要且独有的对象:jQuery对象,所以我们在页面元素选择或执行功能函数的时候就可以这么写:

$(function(){});           //执行一个匿名函数
$('#box');                    //进行执行的ID元素选择
$('#box').css('color','red');         //执行函数功能

由于“$”本身就是jQuery 对象的缩写,那么也就是说上面的代码我们可以写成如下形式:

jQuery(function(){});
jQuery('#box');
jQuery('#box').css('color','red');


实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表格</title>
    <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
    <script>
        $(function(){
            $('#box').css('color','red');
        });
//        alert($===jQuery);
 </script>
</head>
<body>
<div id="box">jQuery语法</div>
</body>
</html>

jQuery 的加载模式

我们在之前的代码一直在使用$(function(){});这段代码进行首尾包裹,你知道为什么要这么做吗?

原因是我们的jQuery 库文件是在body元素之前加载的,我们必须等待所有的网页代码加载之后,才能执行加载JavaScript代码,否则就无法获取

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表格</title>
    <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
    <script>
            $('#box').css('color','red');
    </script>
</head>
<body>
<div id="box">jQuery语法</div>
</body>
</html>

所以我们以前的JavaScript给我们提供了:

window.onload=function(){};           //JavaScript等待加载

我们的jQuery给我们提供了:

$(document).ready(function(){});             //jQuery等待加载


两者的区别:

1. 执行时机

window.onload :必须等待网页加载完毕(包括图片)才能执行包裹代码。

$(document).ready(function(){}) :只需等待网页中的DOM结构加载完毕,就能执行包裹的代码。效果更高


2.执行次数

window.onload 只能执行一次,如果第二次,那么第一次的执行就会被覆盖

$(document).ready(function(){}) :无论执行多少次都不会被覆盖掉

示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表格</title>
    <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
    <script>
//        window.onload=function(){
//            alert(1)
//        };
//        window.onload=function(){
//            alert(2)
//        };
 $(document).ready(function(){
            alert(1)
        });
         $(document).ready(function(){
              alert(2)
         })
    </script>
</head>
<body>
<div id="box">jQuery语法</div>
</body>
</html>


3.简写

window.onload  无

$(document).ready(function(){})     $(function (){});


在实际的应用中,我们很少直接去使用window.onload,因为他需要等待图片之类的大型元素加载完毕之后才能执行JS代码,如果遇到网速较慢的情况下,页面已经全部展开,图片还在缓慢加载,这时页面上任何的JS交互功能全部处于假死状态,比如一些下拉菜单什么的。



下一节
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表格</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script> // window.onload=function(){ // alert(1) // }; // window.onload=function(){ // alert(2) // }; // $(document).ready(function(){ // alert(1) // }); // $(document).ready(function(){ // alert(2) // }) </script> </head> <body> <div id="box">jQuery语法</div> </body> </html>
提交 重置代码
章节 评论 笔记 课件
  • 取消 回复 发送
  • 取消 发布笔记 发送