单击时按钮显示错误的颜色

时间:2014-05-20 08:33:39

标签: javascript jquery css

我的网站包含按钮,每个按钮代表一种颜色,如果用户点击一个颜色,它应该改变容器div的颜色,直到最近才工作但现在当我点击颜色时,我实际上是什么获取是我的数组中的下一个颜色,其中包含颜色代码,希望有人可以帮我弄清楚为什么我会得到不同颜色的按钮应该给我的颜色

包含我的代码的代码笔的链接 http://codepen.io/anon/pen/myfjn

$("document").ready( function (){

var noteColourArray = [];
noteColourArray[0] = "#03CEC2"; 
noteColourArray[1] = "#ADC607";
noteColourArray[2] = "#ffdd00";
noteColourArray[3] = "#f7941f";

//Loop through noteColourArray and append new button for each item
for (var i = 0, len = noteColourArray.length; i < len; i++) {
    noteCreate.noteCreateContainer.append($("<button>", {class: "colourSelect", value: noteColourArray[i] }).css("background-color", noteColourArray[i]).click(setBackgroundColour)) 
}

function setBackgroundColour()
{
    $("#noteCreateContainer").css("background-color", noteColourArray[$(this).index()] )
    return false;
}

});

4 个答案:

答案 0 :(得分:0)

更改函数setBackgroundColour,如下所示;

function setBackgroundColour()
{
    $("#noteCreateContainer").css("background-color", noteColourArray[$(this).index() - 1] )
    return false;
}

http://codepen.io/anon/pen/GqepC

答案 1 :(得分:0)

更改

    #stickerList 
{
    position: absolute;
    height: 500px;
    width: 3rem;
    background-color:grey;
    margin-top: 0;
    display: block;
}

要:

    #stickerList 
{
    position: absolute;
    height: 500px;
    width: 3rem;

    margin-top: 0;
    display: block;
}

答案 2 :(得分:0)

更改功能:

  function setBackgroundColour()
  {
      $("#noteCreateContainer").css("background-color", noteColourArray[$(this).index()] );
    return false;
  }

TO:

 function setBackgroundColour()
  {
      $("#noteCreateContainer").css("background-color", noteColourArray[$(this).index()-1] );
    return false;
  }

答案 3 :(得分:0)

var noteColourArray = [];
noteColourArray[0] = "#03CEC2"; 
noteColourArray[1] = "#ADC607";
noteColourArray[2] = "#ffdd00";
noteColourArray[3] = "#f7941f";

$(document).ready(function(){
    for(var i = 0; i < noteColourArray.length; i++) {
        $('body').append('<button class="colorize">Press Me!</button>');
    }

    $('button.colorize').click(function(){
        $('body').css('backgroundColor', noteColourArray[$(this).index()]);
    });
});

小提琴:

http://jsfiddle.net/2s8SW/1/

相关问题