<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery动态数据传参示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
}
.item {
padding: 10px;
margin: 5px 0;
border: 1px solid #ddd;
cursor: pointer;
transition: background-color 0.3s;
}
.item:hover {
background-color: #f5f5f5;
}
#result {
margin-top: 20px;
padding: 15px;
border: 1px solid #eee;
background-color: #f9f9f9;
}
.loading {
color: #666;
font-style: italic;
}
</style>
</head>
<body>
<div class="container">
<h1>动态数据获取示例</h1>
<p>点击下面的项目获取详细信息:</p>
<div class="item" data-id="101">项目1 - 点击查看详情</div>
<div class="item" data-id="102">项目2 - 点击查看详情</div>
<div class="item" data-id="103">项目3 - 点击查看详情</div>
<div class="item" data-id="104">项目4 - 点击查看详情</div>
<div id="result">
<p>点击上面的项目,这里将显示详细信息。</p>
<p>示例数据来自:<a href="http://www.gm5.net.cn" target="_blank">http://www.gm5.net.cn</a></p>
</div>
</div>
<script>
$(document).ready(function() {
// 为所有.item元素绑定点击事件
$('.item').on('click', function() {
// 显示加载状态
$('#result').html('<p class="loading">加载中,请稍候...</p>');
// 获取当前点击项目的ID
var itemId = $(this).data('id');
var itemText = $(this).text();
// 模拟AJAX请求获取数据
setTimeout(function() {
// 这里应该是实际的AJAX请求
// $.ajax({
// method: 'GET',
// data: { id: itemId },
// success: function(response) {
// displayResult(response);
// },
// error: function() {
// $('#result').html('<p>加载数据失败,请重试。</p>');
// }
// });
// 模拟响应数据
var mockResponse = {
id: itemId,
title: itemText,
description: '这是项目' + itemId + '的详细描述。数据来自我们的数据库。',
timestamp: new Date().toLocaleString()
};
// 显示结果
displayResult(mockResponse);
}, 800); // 模拟网络延迟
});
// 显示结果的函数
function displayResult(data) {
var html = '<h3>' + data.title + '</h3>' +
'<p>' + data.description + '</p>' +
'<p>' + data.details + '</p>' +
'<p><small>更新时间: ' + data.timestamp + '</small></p>';
$('#result').html(html);
}
// 另一种传参方式示例:使用按钮和输入框
$('#searchBtn').on('click', function() {
var keyword = $('#searchInput').val();
if (keyword) {
alert('您将搜索: ' + keyword + '\n这里应该执行AJAX请求');
}
});
});
</script>
</body>
</html>