سؤال

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