为什么我的jquery不改变我的div?

时间:2015-10-07 14:40:18

标签: javascript jquery html css

我尝试更改顶部div,因此当选择任一按钮时,它会根据点击的按钮更改它。

HTML

    <div class="bulb" id="bulb1"></div>
    <div class="bulb" id="bulb2"></div>
    <button id="blue">blue</button>
    <button id="yellow">yellow</button>

JQUERY

$( document ).ready(function() {

    // initial load up coverts to this colour
    $('.bulb1').css("background-color","black");    

    //call the colour change functions when clicked
    $('#blue').click("background-color", "setBlue");
    $('#yellow').click("background-color", "setYellow");

});

function setYellow(){

    $('#bulb1').css("background-color","#yellow");

}

function setBlue(){

    $('#bulb1').css("background-color","#blue");

}

5 个答案:

答案 0 :(得分:3)

尝试这样的事情:

$('#blue').click(function() {
    $('#bulb1').css({
        'background-color' : 'blue'
    });
});

或者

$('#blue').click(function() {
    setBlue();
});

function setBlue() {
    $('#bulb1').css({
       'background-color': 'blue'
     });    
}

您可以重构代码,如:

$(document).ready(function() {

    // initial load up coverts to this colour
    setColor('black');  

    //call the colour change functions when clicked
    $('#blue').click(function() {
      setColor('blue');
    });

    $('#yellow').click(function() {
      setColor('yellow');
    });

});

function setColor(color) {    
    $('#bulb1').css({
       'background-color': color
     });    
}

答案 1 :(得分:1)

您最初选择了错误的元素:

$('.bulb1').css("background-color","black");

应该是

$('#bulb1').css("background-color","black");

$('.bulb').css("background-color","black");

取决于您尝试选择的元素。

答案 2 :(得分:1)

根据您的代码进行更正和解决方案 -

$( document ).ready(function() {

    // initial load up coverts to this colour
    $('#bulb1').css("background-color","black");    

    //call the colour change functions when clicked
    $('#blue').click(function(){
        setBlue();
    });

    $('#yellow').click(function(){
        setYellow();
    });
});

function setYellow(){
    $('#bulb1').css("background-color","yellow");
}

function setBlue(){
    $('#bulb1').css("background-color","blue");
}

答案 3 :(得分:0)

Demo

$( document ).ready(function() {

    // initial load up coverts to this colour
    $('.bulb').css("background-color","black");    

    //call the colour change functions when clicked
    $('#blue').click(function()
    {
        $('#bulb1').css("background-color","blue");
    });
    $('#yellow').click(function()
    {
        $('#bulb1').css("background-color","yellow");
    });

});

答案 4 :(得分:0)

试试这个:

$('#yellow').click(setYellow);
$('#blue').click(setBlue);

或委派click命令来监听文档中元素的“click”事件:

$(document).delegate('#yellow', 'click', setYellow);
$(document).delegate('#blue', 'click', setBlue);