jQuery is a very popular JavaScript library that can simplify developers’ JavaScript programming and improve development efficiency. In web development, in order to provide a better user experience, we often need to make style changes to page elements. This article will introduce how jQuery implements the function of changing the color of selected items.
1. HTML structure
First, we need to add some list elements to HTML to demonstrate the effect of changing the color of the selected item. The following is a simple HTML structure:
Aul
element is defined here, which contains fourli
elements. When the user clicks on one of theli
elements, we set the element to the selected state and change its background color.
2. jQuery to realize the color change of the selected item
Next, we need to use jQuery to achieve the color change effect when the user clicks on the list item. The following are the specific steps:
li
elements through the jQuery selector and bind theclick
event to them.$(document).ready(function(){ $("#list li").click(function(){ // TODO: 点击事件处理逻辑 }); });
li
element, we need to add a CSS classselected
and remove all other list itemsselected
Class.$("#list li").click(function(){ // 添加选中状态 $(this).addClass('selected'); // 移除其他元素的选中状态 $(this).siblings().removeClass('selected'); });
.selected { background-color: #f5f5dc; }
The complete jQuery code is as follows:
$(document).ready(function(){ $("#list li").click(function(){ // 添加选中状态 $(this).addClass('selected'); // 移除其他元素的选中状态 $(this).siblings().removeClass('selected'); }); });
三, Effect jquery implements color change of selected items
The final effect is shown in the figure below:
4. Summary
This article introduces how to use jQuery to achieve selection The function of item changing color. Through studying this article, you have learned how to access DOM elements, add and remove CSS classes, and update the page in real time through jQuery. I hope this article can help you learn jQuery and improve web development efficiency.
The above is the detailed content of jquery implements color change of selected items. For more information, please follow other related articles on the PHP Chinese website!