jQuery 是一个快速、小巧且功能丰富的 JavaScript 库。它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互,使得 Web 开发更加便捷。
jQuery 主要有以下几种类型:
可以通过以下几种方式引入 jQuery:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Example</title>
<!-- 引入 jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Hello, jQuery!</h1>
<script>
// 使用 jQuery
$(document).ready(function() {
$('h1').css('color', 'blue');
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Example</title>
<!-- 引入本地 jQuery 文件 -->
<script src="path/to/jquery.min.js"></script>
</head>
<body>
<h1>Hello, jQuery!</h1>
<script>
// 使用 jQuery
$(document).ready(function() {
$('h1').css('color', 'blue');
});
</script>
</body>
</html>
原因:可能是 CDN 地址错误或网络问题。
解决方法:
原因:可能是代码写在 jQuery 加载之前。
解决方法:
$(document).ready()
中执行。原因:项目中引入了多个不同版本的 jQuery。
解决方法:
jQuery.noConflict()
解决版本冲突问题。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Example</title>
<!-- 引入 jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Hello, jQuery!</h1>
<button id="changeColor">Change Color</button>
<script>
$(document).ready(function() {
$('#changeColor').click(function() {
$('h1').css('color', 'red');
});
});
</script>
</body>
</html>
在这个示例中,当点击按钮时,页面中的 <h1>
标签的文字颜色会变为红色。