我在列表中有几个项目,并希望通过应用一些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()方法)更好的解决方案,因为关注点的分离将使您的代码更易于管理和读取.