문제

Hello guys i'm trying to create a jquery function when he click the select button on the first time the background will change to white and if he click again it will change to blue vice versa

<select name="contact" class="changeBg">
     <option value="">Change!</option>
     <option value="">Changes!</option>
</select>

$('.changeBg').click(function() {
    $(this).css('background-color', 'green');
 });
도움이 되었습니까?

해결책

You can try using .toggleClass( className, switch ) to switch between two classes.

Live Demo

$('.changeBg').click(function() {
    $(this).toggleClass('white blue');
});

다른 팁

Try to toggle it with name like

$('select[name="contact"]').change(function(){
     $(this).toggleClass('class1 class2');
});

For the both classes you can give background colors as like

.class1 {background-color:pink;}
.class2 {background-color:white;}

Even you can choose class name as like

$('.changeBg').change(function(){
     $(this).toggleClass('class1 class2');
});

But better you can switch or toggle 2different classes ratherthan the changebg.Because if you toggle that class then for the second time the change event wont be work.

Fiddle Demo

.toggleClass()

$('.changeBg').click(function() { //you can use change event
    $(this).toggleClass('BgColor');
});

CSS

.changeBg { /* no need if your background is already white */
    background-color:#fff;
}
.BgColor {
    background-color:blue;
}
$(function () {
        $('.changeBg').change(function () {
            $(this).toggleClass('whileClass BlackClass');
        });
    });

    .whileClass {
        background-color: pink;
    }

    .BlackClass {
        background-color: white;
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top