posts - 501,comments - 0,views - 23802

相关视频

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">
  <title>Document</title>
  <!--
  <script></script>
  jQuery可以写在这里
  -->
</head>
<body>
  
  <!--
  <script></script>
  jQuery也可以写在这里,写在这里效率高一点。
  -->
</body>
</html>

jQuery的写法主要是匿名函数自调用

匿名函数自调用

为什么参数要有window和undefined

(function( window, undefined ) {
	
}
)(window);

window.jQuery = window.$ = jQuery; window多了两个属性,两个属性的值都是jQuery,只需要搞懂jQuery是什么。

jQuery是个函数,执行返回的是实例对象。

jQuery = function( selector, context ) {
	// The jQuery object is actually just the init constructor 'enhanced'
	return new jQuery.fn.init( selector, context, rootjQuery );
}

测试时用.js未压缩的版本,上线的时候用.min.js压缩的版本。

引用js必须在使用之前。

<script type="text/javascript" src="js/jquery-1.10.1.js"></script>
<script type="text/javascript">
  // 绑定文档加载完成的监听,加监听就是绑定回调函数
  $(function () {
    $('#btn2').click(function  () {//给btn2绑定点击监听
      alert($('#username').val())
    })
  })
</script>

整体代码

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>01_初识jQuery</title>

  <!--
  方式一: 使用原生JS实现功能
  -->
  <script type="text/javascript">
    window.onload = function () {
      var btn = document.getElementById('btn1')
      btn.onclick = function () {
        alert(document.getElementById('username').value)
      }
    }
  </script>
  <!--
  方式二: 使用jQuery实现功能
    1. 引入jQuery库
      * 本地引入
      * 远程引入
    2. 使用jQuery函数和jQuery对象编码
  -->
  <script type="text/javascript" src="js/jquery-1.10.1.js"></script>
  <script type="text/javascript">
    // 绑定文档加载完成的监听,加监听就是绑定回调函数
    $(function () {
      $('#btn2').click(function  () {//给btn2绑定点击监听
        alert($('#username').val())
      })
    })
  </script>
</head>
<body>
<!--
需求: 点击"确定"按钮, 提示输入的值
-->

用户名: <input type="text" id="username">
<button id="btn1">确定(原生版)</button>
<button id="btn2">确定(jQuery版)</button>
</body>

</html>

结果展示

posted on   垂序葎草  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 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 31 1 2 3 4 5

点击右上角即可分享
微信分享提示