I am using this code to load some content of a div as well as change the color of the tab the user clicked on. I'm having trouble figuring out how to make the background color change back once the user clicks on something else. How would I do that?

$(function() {
        $('#tab-1').click(function() {
            var tabcontent = "<?php echo preg_replace("/\r?\n/", "\\n", addslashes($tabcontent[0]));?>";
            document.getElementById('top-tabs-content').innerHTML = tabcontent;
            $(this).css("background-color","#F7C703");
        });
    });
有帮助吗?

解决方案

$(function() {
    $('#tab-1').click(function() {
        var tabcontent = "<?php echo preg_replace("/\r?\n/", "\\n", addslashes($tabcontent[0]));?>";
        document.getElementById('top-tabs-content').innerHTML = tabcontent;
        $('.tabclass').css("background-color","#defaultcolour");
        $(this).css("background-color","#F7C703");
    });
});

Add a class to the elements, then before applying the colour to clicked element, reset all the elements with the default colour.

其他提示

You can bind a click handler to the document object and use the .closest() method:

$(document).on('click', function(e) {
    if ( !$(e.target).closest('#tab-1').length ) {
       $('#tab-1').css("background-color", '');
    }
});

http://jsfiddle.net/6g8g7/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top