【发布时间】:2014-05-07 07:43:19
【问题描述】:
我有一个 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,这似乎得到了我从这篇文章中寻求的结果,颜色按钮从未打算用作表单提交按钮,一个单独的按钮将负责那个
【问题讨论】:
-
尝试将
click方法与$('.colourSelect').each(function() { $(this).on('click', function(e) { e.preventDefault(); setBackgroundColour(); })});之类的方法绑定 -
必须有其他东西将 CSS 改回来。设置一个属性修改断点,这样你就可以看到它是什么。
-
你能解释一下它是如何工作的吗?对 javascript/jquery 还是很陌生,但想了解
-
@NathanAnderson 您绑定点击事件的方法应该可以正常工作。
-
@NathanAnderson,当您发布表单时,您的颜色正在变回,因此页面将重新加载。
e.preventDefault阻止表单回发,因此页面不会被重置
标签: javascript jquery html css function