简体   繁体   中英

How can I shorten this jQuery code?

Sorry for the non-saying title, but I have a question on how to shorten a piece of jQuery code:

$(function() {
    $("#profile1").click(function() {
        $("#profile1").addClass("focused");
        $("#profile2").removeClass("focused");
        $("#profile3").removeClass("focused");
    });
    $("#profile2").click(function() {
        $("#profile1").removeClass("focused");
        $("#profile2").addClass("focused");
        $("#profile3").removeClass("focused");
    });
    $("#profile3").click(function() {
        $("#profile1").removeClass("focused");
        $("#profile2").removeClass("focused");
        $("#profile3").addClass("focused");
    });
});

For what I can see, a toggleClass wouldn't do it, since I can press that object two times in a row and therefore make multiple objects being focused at the same time, while I'm looking for some kind of a switch, where only one object can be in focus (ie have the class 'focused') at a time.

This is me being kind of a beginner, but I'm guessing I should involve 'this' somewhere, but I can't figure out how.

Thanks in advance! You guys rock!

Remove the class from all of them, then add it to the targeted one only. Also, use a single event handler only and reference the event target dynamically.

$(function() {
    var $profiles = $("#profile1, #profile2, #profile3");
    $profiles.click(function(e) {
        $profiles.removeClass("focused");
        $(this).addClass("focused"); // or use `e.target` instead of `this`
    });
});

You might also use a class .profile instead of ids to select the elements now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM