我在列表中有几个项目,我想通过应用一些 css 样式(可能是背景颜色等)来突出显示用户点击的项目。
我的 HTML 看起来像这样:
<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 检索所选项目:
$('.thumbnail').click(function(e) {
e.preventDefault();
???
})
最佳答案
您可以使用 jQuery 的 class management methods (即 addClass()
和 removeClass()
在这种情况下)在所选项目上添加一个类并从所有其他项目中删除相同的类(如果您只想要一次选择一个)。
//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 中添加:
.highlight {
background-color: cyan;
font-weight: bold;
}
这是比直接从 jQuery/Javascript 更改 CSS 属性(例如使用 .css()
方法)更好的解决方案,因为关注点分离将使您的代码更易于管理和可读。
关于javascript - 如何使用 jquery 突出显示选定的列表项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15301356/