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的写法主要是匿名函数自调用
(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>
结果展示
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)