문제

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