按钮单击暂时更改div背景颜色,而不是永久按预期 [英] button click temporarily changes div background color, not permanently as intended
本文介绍了按钮单击暂时更改div背景颜色,而不是永久按预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个div,它保存2个输入字段和按钮来改变div的背景颜色点击,问题是当我点击按钮(每个代表一种颜色),背景颜色只有一个闪光灯改变不是永久性的
I have a div which holds 2 input fields and buttons to change the background color of the div on click, the problem is when I click on the buttons(each one represents a color), the background color only changes for a flash of a second, not permanently
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
在函数setBackgroundColour()
的结尾,这似乎得到了我从这篇文章中得到的结果,颜色按钮从来不打算作为表单提交按钮,一个单独的按钮将处理
UPDATE: I have added return false
at the end of function setBackgroundColour()
which seemed to get the result of what I seeked from this post, the colour buttons were never intended as form submit buttons, a separate button will take care of that
推荐答案
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]);
});
});
这篇关于按钮单击暂时更改div背景颜色,而不是永久按预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文