如何使用jquery突出显示所选列表项? [英] How can I highlight a selected list item with jquery?
问题描述
我在列表中有几个项目,并希望通过应用一些css样式,可能是背景颜色等来突出显示用户点击的项目。
I have several items in a list and want to highlight the one a user clicks on by applying some css style, maybe a background color etc.
我的HTML看起来像这样:
My HTML looks like this:
<ul class="thumbnails">
<li>
<a href="#" class="thumbnail">
<img class="giftthumb" src='thumb1.jpg' alt="">
<span class="gifttitle">Thumb1</span>
</a>
</li>
<li>
<a href="#" class="thumbnail">
<img class="giftthumb" src='thumb2.jpg' alt="">
<span class="gifttitle">Thumb3</span>
</a>
</li>
<li>
<a href="#" class="thumbnail">
<img class="giftthumb" src='thumb3.jpg' alt="">
<span class="gifttitle">Thumb3</span>
</a>
</li>
</ul>
jQUery检索所选项目:
jQUery to retrieve selected item:
$('.thumbnail').click(function(e) {
e.preventDefault();
???
})
推荐答案
你可以使用jQuery的类管理方法(即 addClass()
和 removeClass()
在这种情况下)在所选项目上添加一个类,并从所有其他项目中删除相同的类(如果您希望一次只选择一个)。 / p>
You could use jQuery's class management methods (namely addClass()
and removeClass()
in this case) to add a class on the selected item and remove the same class from all the other items (if you want only one selected at a time).
//save class name so it can be reused easily
//if I want to change it, I have to change it one place
var classHighlight = 'highlight';
//.click() will return the result of $('.thumbnail')
//I save it for future reference so I don't have to query the DOM again
var $thumbs = $('.thumbnail').click(function(e) {
e.preventDefault();
//run removeClass on every element
//if the elements are not static, you might want to rerun $('.thumbnail')
//instead of the saved $thumbs
$thumbs.removeClass(classHighlight);
//add the class to the currently clicked element (this)
$(this).addClass(classHighlight);
});
然后在你的CSS中添加:
Then in your CSS just add:
.highlight {
background-color: cyan;
font-weight: bold;
}
这比直接从jQuery / Javascript更改CSS属性更好(使用 .css()
方法,例如),因为关注点的分离将使您的代码更易于管理和阅读。
This is a better solution than changing CSS properties directly from jQuery/Javascript (with the .css()
method for example), because separation of concerns will make your code more manageable and readable.
这篇关于如何使用jquery突出显示所选列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!