我已经构建了此功能,该功能在用户单击按钮时执行;它将一个列表和2个按钮元素插入到以表格包装的有序列表中。但是,每当我单击“生成”按钮时,它都会立即生成新元素,然后立即重定向到表单的“操作/处理php”页面,由于未填写字段等,该页面会重定向回到上一页。 ,所以我对为什么要处理表格感到困惑?
这是我的JS函数:
function spawnSilly() //spawn chapters function
{
var div = document.createElement("LI"); //creating elements
var input = document.createElement("INPUT");
var button = document.createElement("BUTTON");
var del_button = document.createElement("BUTTON")
input.setAttribute("type", "text"); //setting attributes
input.setAttribute("name", "chapterInput" + stringNumber);
input.setAttribute("placeholder", "Title");
input.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.setAttribute("type", "button");
button.setAttribute("onClick", "redirect()");
button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.innerHTML = "Edit";
div.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.innerHTML = "Delete Chapter";
del_button.setAttribute("onClick", "removeElement(this.id)")
div.appendChild(input) //appending to list
div.appendChild(button)
div.appendChild(del_button);
var chapterNumber = getCount(document.getElementById('spawnList'), false) //setting number of chapter
var number = $('#spawnList').children(); //fetching number of children in list
var stringNumber = String(number) //setting chapter number to string for name attribute in input
var list = document.getElementById("spawnList");
list.insertBefore(div, list.childNodes[number]); //inserting one after another
var newChapterNumber = chapterNumber + 1; //setting elements class as their chapter number
input.setAttribute("class", newChapterNumber);
button.setAttribute("class", newChapterNumber);
div.setAttribute("class", newChapterNumber);
del_button.setAttribute("class", newChapterNumber);
input.setAttribute("index", newChapterNumber);
button.setAttribute("index", newChapterNumber);
div.setAttribute("index", newChapterNumber);
del_button.setAttribute("index", newChapterNumber);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="title-processing.php" method="post">
<ol id="spawnList">
</ol>
<button id="spawnbtn" onClick="spawnSilly();">Add Chapter</button>
<button type="submit" name="Submit">Save</button>
</form>
任何帮助都会很棒! :)
答案 0 :(得分:1)
按钮的默认type=
是submit
-因此,通过省略type=
,系统会添加type=submit
,因此您的按钮:
<button id="spawnbtn" onClick="spawnSilly();">Add Chapter</button>
实际上是
<button type='submit' id="spawnbtn" onClick="spawnSilly();">Add Chapter</button>
明确指定类型以停止提交表单:
<button type='button' id="spawnbtn" onClick="spawnSilly();">Add Chapter</button>