在动态生成的HTML表格中实现星级评分,需要结合动态DOM生成、CSS样式设计和JavaScript事件处理三个部分,核心是先构建表格的基础结构,再在指定单元格中插入评分组件并绑定交互逻辑。

基础准备:样式与静态结构
首先我们需要定义星级评分的基础CSS样式,以及动态表格的容器结构。星级评分通常使用空心和实心星星的切换来表示评分状态,这里用CSS伪元素和类名切换实现。
/* 星级评分容器样式 */
.star-rating {
display: inline-flex;
gap: 4px;
cursor: pointer;
}
/* 单个星星基础样式 */
.star {
font-size: 20px;
color: #ccc;
transition: color 0.2s;
}
/* 选中状态的星星样式 */
.star.active {
color: #ffc107;
}
/* 表格基础样式 */
#dynamicTable {
border-collapse: collapse;
width: 100%;
margin-top: 20px;
}
#dynamicTable th, #dynamicTable td {
border: 1px solid #ddd;
padding: 12px;
text-align: center;
}
#dynamicTable th {
background-color: #f5f5f5;
}
动态生成表格并插入评分组件
假设我们从后端获取到的数据是一个数组,每个元素包含表格行的其他信息和初始评分值,我们需要遍历数据动态生成表格行,同时在评分列的单元格中插入星级评分组件。
// 模拟后端返回的动态数据
const tableData = [
{ id: 1, name: '商品A', initialScore: 3 },
{ id: 2, name: '商品B', initialScore: 5 },
{ id: 3, name: '商品C', initialScore: 1 }
];
// 动态生成表格的主函数
function generateDynamicTable(data) {
const table = document.getElementById('dynamicTable');
// 清空表格原有内容
table.innerHTML = '';
// 创建表头
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
['ID', '名称', '星级评分'].forEach(text => {
const th = document.createElement('th');
th.textContent = text;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// 创建表体并遍历数据生成行
const tbody = document.createElement('tbody');
data.forEach(item => {
const row = document.createElement('tr');
// ID列
const idCell = document.createElement('td');
idCell.textContent = item.id;
row.appendChild(idCell);
// 名称列
const nameCell = document.createElement('td');
nameCell.textContent = item.name;
row.appendChild(nameCell);
// 评分列:插入星级评分组件
const scoreCell = document.createElement('td');
const ratingContainer = createStarRating(item.id, item.initialScore);
scoreCell.appendChild(ratingContainer);
row.appendChild(scoreCell);
tbody.appendChild(row);
});
table.appendChild(tbody);
}
// 创建单个星级评分组件的函数
function createStarRating(rowId, initialScore) {
const container = document.createElement('div');
container.className = 'star-rating';
container.dataset.rowId = rowId; // 存储行ID,方便后续获取对应数据
// 生成5颗星星
for (let i = 1; i <= 5; i++) {
const star = document.createElement('span');
star.className = 'star';
star.dataset.score = i; // 存储当前星星对应的分值
// 如果初始分值大于等于当前星星序号,设置为选中状态
if (i <= initialScore) {
star.classList.add('active');
}
// 绑定鼠标悬停和点击事件
star.addEventListener('mouseover', handleStarHover);
star.addEventListener('mouseout', handleStarOut);
star.addEventListener('click', handleStarClick);
container.appendChild(star);
}
return container;
}
评分交互事件处理
星级评分需要支持鼠标悬停预览、点击确认评分、鼠标移出恢复已选状态三个交互逻辑,同时需要把评分结果和对应的表格行关联起来。
// 存储所有行的评分数据,键为行ID,值为评分
const scoreMap = {};
// 初始化评分数据
function initScoreMap(data) {
data.forEach(item => {
scoreMap[item.id] = item.initialScore;
});
}
// 鼠标悬停星星时的处理逻辑
function handleStarHover(e) {
const star = e.target;
const container = star.parentElement;
const hoverScore = parseInt(star.dataset.score);
// 遍历当前容器内的所有星星,分值小于等于悬停分值的设置为激活状态
const allStars = container.querySelectorAll('.star');
allStars.forEach(s => {
const sScore = parseInt(s.dataset.score);
if (sScore <= hoverScore) {
s.classList.add('active');
} else {
s.classList.remove('active');
}
});
}
// 鼠标移出星星容器时的处理逻辑
function handleStarOut(e) {
const container = e.target.parentElement;
const rowId = parseInt(container.dataset.rowId);
const currentScore = scoreMap[rowId];
// 恢复为当前已存储的评分状态
const allStars = container.querySelectorAll('.star');
allStars.forEach(s => {
const sScore = parseInt(s.dataset.score);
if (sScore <= currentScore) {
s.classList.add('active');
} else {
s.classList.remove('active');
}
});
}
// 点击星星确认评分的处理逻辑
function handleStarClick(e) {
const star = e.target;
const container = star.parentElement;
const rowId = parseInt(container.dataset.rowId);
const clickScore = parseInt(star.dataset.score);
// 更新存储的评分数据
scoreMap[rowId] = clickScore;
// 更新星星显示状态
const allStars = container.querySelectorAll('.star');
allStars.forEach(s => {
const sScore = parseInt(s.dataset.score);
if (sScore <= clickScore) {
s.classList.add('active');
} else {
s.classList.remove('active');
}
});
console.log(`行ID为${rowId}的评分更新为:${clickScore}`);
}
初始化与完整调用
最后我们只需要调用初始化函数,传入模拟数据即可完成整个动态表格和星级评分的渲染。
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
initScoreMap(tableData);
generateDynamicTable(tableData);
});
注意事项
- 如果动态表格后续会重新渲染,需要提前解绑旧的事件监听器,避免内存泄漏,或者使用事件委托的方式绑定评分事件。
- 如果需要支持半星评分,可以调整星星的样式为半星图标,同时修改分值判断逻辑为小数判断。
- 评分数据如果需要同步到后端,可以在点击事件的回调中发起对应的接口请求,把行ID和评分值作为参数传递。
动态生成表格中的星级评分核心是保证每个评分组件和对应的表格行数据关联,通过dataset属性存储关联ID是最简便的实现方式,后续扩展功能也更方便。
HTMLJavaScriptCSS星级评分动态表格修改时间:2026-07-03 04:42:28