jquery 案例
以下是一些实用的 jQuery 案例,涵盖常见功能实现和交互效果:
动态内容加载
通过 AJAX 加载内容并更新页面部分区域:
$('#loadBtn').click(function() {
$.ajax({
url: 'data.html',
method: 'GET',
success: function(response) {
$('#contentArea').html(response);
}
});
});
表单验证
实现客户端表单验证:
$('#submitForm').submit(function(e) {
var email = $('#email').val();
if (!email.includes('@')) {
e.preventDefault();
$('#errorMsg').text('请输入有效的邮箱地址');
}
});
动画效果
创建平滑滚动效果:
$('a[href^="#"]').click(function() {
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top
}, 800);
});
交互式菜单
实现下拉菜单功能:
$('.menuItem').hover(
function() {
$(this).find('.subMenu').slideDown(200);
},
function() {
$(this).find('.subMenu').slideUp(200);
}
);
图片轮播
基础图片轮播实现:
var currentIndex = 0;
var images = $('.slider img');
var totalImages = images.length;
function cycleImages() {
images.hide();
currentIndex = (currentIndex + 1) % totalImages;
images.eq(currentIndex).fadeIn(1000);
setTimeout(cycleImages, 3000);
}
cycleImages();
动态表格操作
添加和删除表格行:
$('#addRow').click(function() {
var newRow = '<tr><td>New Item</td><td><button class="removeRow">删除</button></td></tr>';
$('#dataTable').append(newRow);
});
$(document).on('click', '.removeRow', function() {
$(this).closest('tr').remove();
});
响应式设计
根据窗口大小调整布局:
$(window).resize(function() {
if ($(window).width() < 768) {
$('.sidebar').hide();
} else {
$('.sidebar').show();
}
});
这些案例展示了 jQuery 在 DOM 操作、事件处理、动画效果和 AJAX 交互方面的典型应用。实际开发中可根据需求组合这些基础模式实现更复杂的功能。







