如何实现点击列表项使其变为红色并添加删除线?
解决点击新增列表项无样式变化的问题
需求
点击新增的列表项时,将其文字颜色改为红色,并添加删除线。
问题原因
你尝试的点击事件代码无效,核心问题是:动态生成的DOM元素无法通过直接绑定事件的方式触发响应。页面加载时$("li").click()只会给当时已存在的li绑定事件,后续通过append新增的li不会继承这个事件。
另外,你的CSS已经定义了.complete类(包含红色文字和删除线样式),直接使用类切换比手动修改css()更简洁易维护。
解决方案
修改JavaScript部分,使用事件委托绑定点击事件,并利用已有的CSS类实现样式切换:
$(document).ready(function(){ // 添加新列表项的逻辑 $('#showForm').click(function(){ var liText = $('#itemDescription').val(); // 避免添加空内容的列表项 if(liText.trim()){ $('#list').append('<li>'+liText+'</li>'); // 添加后清空输入框 $('#itemDescription').val(''); } }); // 事件委托:给父元素绑定事件,监听子元素li的点击 $('#list').on('click', 'li', function(){ // 切换.complete类,实现点击添加/移除样式 $(this).toggleClass('complete'); }); });
代码说明
- 事件委托:通过
$('#list').on('click', 'li', function(){...}),把点击事件绑定到页面加载时已存在的父元素#list上,后续新增的li触发点击时,事件会冒泡到父元素,从而触发处理函数。 - toggleClass:点击li时切换
.complete类,一次点击添加样式,再次点击移除样式(如果需要仅添加不取消,把toggleClass换成addClass即可)。 - 额外优化:添加了空值判断,避免生成空内容的列表项,同时添加后清空输入框,提升用户体验。
完整修改后的HTML代码
<html lang="en"> <head> <meta charset="utf-8"> <title>Ultimate List Maker</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style> * {margin:0; padding:10px; text-align:center;} body {width:80%; margin:40px auto; min-width: 400px; max-width: 600px} header {background:red} #counters {background:lightgreen;font-weight: bold; font-size: 150%;display: flex; justify-content: space-around; flex-wrap: wrap} button {background: #ff9999; width: 100px; } main {background:yellow; min-height: 80px} footer {background:lightblue} button:hover {background: pink} li {list-style: none; font-weight: bold; font-size: 150%} .complete {color: red; text-decoration: line-through} </style> </head> <body> <main> <ul id="list"> <li></li> </ul> <button id="showForm">Add New Item</button> <form id="newItemForm"> <input type="text" id="itemDescription" placeholder="Add description"> <input type="submit" id="add" value="add"> </form> </main> <footer><h2>Making lists since 2018</h2></footer> <script> $(document).ready(function(){ $('#showForm').click(function(){ var liText = $('#itemDescription').val(); if(liText.trim()){ $('#list').append('<li>'+liText+'</li>'); $('#itemDescription').val(''); } }); $('#list').on('click', 'li', function(){ $(this).toggleClass('complete'); }); }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者aummygod
相关产品推荐
相关产品推荐

