2013-05-06 75 views
0

我想要做的是創建一個按鈕,它可以用標籤上指定的顏色來改變div容器的背景顏色。當我在控制檯上運行它時,它說我的變量沒有被指定。更改背景色不起作用。 jQuery

<div class="grid1"> 
    <input id="bgR" type="text"></input> 
    <input id="bgG" type="text"></input> 
    <input id="bgB" type="text"></input> 
    <input id="change_bgColor" type="button" value="Change Background Color"></input> 
</div> 


$('#change_bgColor').click(function(){ 
    var rColor = $('#bgR').val(); 
    var gColor = $('#bgG').val(); 
    var bColor = $('#bgB').val(); 
    var newColor = "rgb("+ rColor +","+ gColor +"," + bColor + ")"; 
    $('#container').css("background-color", newColor); 
}); 

我的代碼確實包含#container我只是沒有發佈在這裏,因爲我不想發佈我所有的代碼。

http://jsfiddle.net/isherwood/muSgn/

+0

是您的單擊事件開除了? – 2013-05-06 17:36:16

+0

適合我... – Prinzhorn 2013-05-06 17:36:57

+0

請發佈確切的錯誤信息。 – Dogbert 2013-05-06 17:37:15

回答

2

添加的元素與該ID '容器' 和一切都很好。

http://jsfiddle.net/isherwood/muSgn/3

<div id="container"> 
    <div class="grid1"> 
     <input id="bgR" type="text"></input> 
     <input id="bgG" type="text"></input> 
     <input id="bgB" type="text"></input> 
     <input id="change_bgColor" type="button" value="Change Background Color"></input> 
    </div> 
</div> 
0

看起來你缺少一些基本的。

你添加jQuery庫,還包喲$(文件)。就緒(){}

支票本上的jsfiddle工作的罰款。

http://jsfiddle.net/saWbn/1/

<div class="grid1"> 
    <input id="bgR" type="text"></input> 
    <input id="bgG" type="text"></input> 
    <input id="bgB" type="text"></input> 
    <input id="change_bgColor" type="button" value="Change Background Color"></input> 
</div> 

<div id="container"> 
this is a container 
    </div>  


    $(document).ready(function() { 
    $('#change_bgColor').click(function(){ 

    var rColor = $('#bgR').val(); 
    var gColor = $('#bgG').val(); 
    var bColor = $('#bgB').val(); 
    var newColor = "rgb("+ rColor +","+ gColor +"," + bColor + ")"; 
    $('#container').css("background-color", newColor); 
}); 

    // Handler for .ready() called. 
}); 
+0

我的JQuery文檔環繞.ready(),就像我的HTML包含div #container一樣,我只是沒有在這裏發佈它們。你的代碼在小提琴上運行良好,但是當我將它複製並粘貼到我的編輯器上並在Chrome上運行它時,它只會更新綠色,並且它甚至不會更新它實際上只是一種設置的顏色。 – 2013-05-06 18:07:30