jquery使用
jQuery 基础用法
jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。以下是 jQuery 的基本使用方法:
引入 jQuery 库
在 HTML 文件中通过 <script> 标签引入 jQuery 库。可以从 CDN 加载:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
选择器 jQuery 使用 CSS 选择器来选取 DOM 元素:
$('p') // 选择所有 <p> 元素
$('#myId') // 选择 id 为 myId 的元素
$('.myClass') // 选择 class 为 myClass 的元素
DOM 操作 jQuery 提供了丰富的 DOM 操作方法:
$('#myDiv').html('<p>New content</p>') // 设置 HTML 内容
$('#myDiv').text('New text') // 设置文本内容
$('#myInput').val('new value') // 设置表单元素的值
事件处理
jQuery 简化了事件绑定和处理:
$('#myButton').click(function() {
alert('Button clicked!')
})
$('#myForm').submit(function(e) {
e.preventDefault()
console.log('Form submitted')
})
动画效果
jQuery 提供了内置的动画方法:
$('#myBox').hide(1000) // 1秒内隐藏元素
$('#myBox').show(500) // 0.5秒内显示元素
$('#myBox').fadeIn() // 淡入效果
$('#myBox').fadeOut() // 淡出效果
$('#myBox').slideUp() // 向上滑动隐藏
$('#myBox').slideDown() // 向下滑动显示
Ajax 请求
jQuery 简化了 Ajax 请求:
$.ajax({
url: 'api/data',
method: 'GET',
dataType: 'json',
success: function(data) {
console.log(data)
},
error: function(error) {
console.error(error)
}
})
// 简写方法
$.get('api/data', function(data) {
console.log(data)
})
$.post('api/save', {name: 'John'}, function(response) {
console.log(response)
})
链式调用
jQuery 支持链式调用:
$('#myDiv')
.css('color', 'red')
.slideUp(200)
.slideDown(200)
实用工具方法
jQuery 提供了一些实用工具方法:
$.each([1, 2, 3], function(index, value) {
console.log(index + ': ' + value)
})
$.extend({}, obj1, obj2) // 对象合并
$.trim(' hello ') // 去除字符串两端空格
插件扩展
jQuery 支持通过插件扩展功能:

// 自定义插件
$.fn.myPlugin = function(options) {
// 插件逻辑
return this.each(function() {
$(this).css('color', options.color)
})
}
// 使用插件
$('p').myPlugin({color: 'blue'})
以上是 jQuery 的核心功能概述。jQuery 的 API 设计简洁直观,大大简化了 JavaScript 开发中的常见任务。






