gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:05 24 4
gpt4 key购买 nike

我有一个 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);
}

更新:我在 function setBackgroundColour() 的末尾添加了 return false 这似乎得到了我从这篇文章中寻找的结果,颜色按钮是从来没有打算作为表单提交按钮,一个单独的按钮将负责

最佳答案

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]);
});
});

关于javascript - 单击按钮临时更改 div 背景颜色,而不是按预期永久更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23511734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com