按钮单击暂时更改div背景颜色,而不是按预期永久更改

时间:2014-05-07 07:43:19

标签: javascript jquery html css function

我有一个div,它包含2个输入字段和按钮,可以在点击时更改div的背景颜色,问题是当我点击按钮(每个按钮代表一种颜色)时,背景颜色只会改变为闪光灯一秒钟,而不是永久性的

var noteCreate =
{
 noteCreateContainer : $("<article>", { id: "noteCreateContainer" }),
 noteForm : $("<form>", { id: "noteFormContainer" }),
 subjectField : $("<input>", { type: "text", placeholder: "Main Heading", id: "subject"}),
noteField : $("<input>", { type: "text", placeholder: "Enter your Note", id: "noteContent" }),
submitNote : $("<button>", { type: "submit", text: "post"}).click(saveFieldInput)
}

noteCreate.noteCreateContainer.appendTo("body");
noteCreate.noteForm.appendTo(noteCreateContainer);

//For each item in array create button
var noteColourArray = [];
noteColourArray[0] = "#03CEC2"; 
noteColourArray[1] = "#ADC607";
noteColourArray[2] = "#ffdd00";
noteColourArray[3] = "#f7941f";

//Loop through noteColourArray and create button for each item
for (var i = 0, len = noteColourArray.length; i < len; i++) {
 noteCreate.noteForm.append($("<button>", {class: "colourSelect", text: noteColourArray[i] }).click(setBackgroundColour)) 
 console.log(noteColourArray)
}

//Change background colour on click
function setBackgroundColour()
{
 $("#noteCreateContainer").css("background-color", noteColourArray[$(this).index()] )
}

noteCreate.subjectField.appendTo(noteFormContainer);
noteCreate.noteField.appendTo(noteFormContainer);
noteCreate.submitNote.appendTo(noteFormContainer);

//Run upon submitting note
//Create class div that shares variables, but each own background-color
function saveFieldInput()
{
//Read input from input fields when note is submitted
 var subjectInput = $("#subject").val();
 console.log(subjectInput);
}

更新:我在return false的末尾添加了function setBackgroundColour(),这似乎是我从这篇文章中得到的结果,颜色按钮从未打算作为表单提交按钮,单独的按钮会处理那个

1 个答案:

答案 0 :(得分:0)

for (var i in noteColourArray) {
    // build the button with pure JS just cause it's faster
    var button = document.createElement('button'),
        buttonText = document.createTextNode(noteColourArray[i]);
    button.className = 'colourSelect';
    button.appendChild(buttonText);

    // append the button
    noteCreate.noteForm.append(button);
}
$('.colourSelect').each(function(index, element) {
    $(this).on('click', function(e) {
        e.preventDefault();

        $("#noteCreateContainer").css("background-color", noteColourArray[index]);
    });
});