相关视频

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 2023-01-10 07:02  垂序葎草  阅读(40)  评论(0编辑  收藏  举报