Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

javascript - How can I highlight a selected list item with jquery?

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.

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 to retrieve selected item:

$('.thumbnail').click(function(e) {
    e.preventDefault();

    ???

})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

Then in your CSS just add:

.highlight {
    background-color: cyan;
    font-weight: bold;
}

jsFiddle Demo

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...