javascript - 如何在onclick事件完成后将“按钮”按钮更改为“提交”按钮onclick而不提交?
问题描述
我有一个按钮,单击该按钮时,会通过onclick
JavaScript 函数动态提示用户提供更多信息:
<button type="button" id="create" onclick="addFields()">create?</button>
将新信息加载到页面后,我希望按钮提交表单:
// .js file
function addFields(){
var container = document.getElementById("initialinfo");
var newInfo = document.createElement('div');
newInfo.setAttribute("id", "createDetails");
newInfo.innerHTML += "divs and checkboxes and radios"
container.appendChild(newInfo);
document.getElementById("create").removeAttribute("onclick");
document.getElementById("create").setAttribute('type', 'submit');
}
不幸的是,当我这样做时,表单不会在下次点击时提交。相反,在onclick
事件之后,按钮(现在是 type submit
)提交表单。如何防止这种行为?
解决方案
您可以在第二次单击按钮时以编程方式触发表单
<form id="myForm" action="..." >
<button type="button" onclick="addFields(event)">continue?</button>
</form>
function addFields({target}){
var container = document.getElementById("initialinfo");
var newInfo = document.createElement('div');
newInfo.setAttribute("id", "createDetails");
newInfo.innerHTML += "divs and checkboxes and radios"
container.appendChild(newInfo);
// here we change the onclick event handler
target.onclick = () => {
const form = document.getElementById('myForm')
form.reportValidity() && form.submit()
}
}
推荐阅读
- c# - Xamarin Forms 日期和时间选择器
- anaconda - 在 Anaconda 的虚拟环境下运行 jupyter notebook 时显示空白页
- jekyll - 将数组传递给包含以循环
- excel - 每当我尝试运行代码时,都会出现错误:预期表达式
- python - 使用 tqdm 与 dask 分布式
- flutter - Flutter:在同一页面中选择过滤器时刷新列表 API
- typescript - TypeScript:如何根据第一个参数的值制作可选的第二个参数
- .net - 如何在 Visual Basic 中将文本框数据添加到数据库
- android - Android 通过 Retrofit 发送 HTTP POST 来触发云功能
- vue.js - 休假过渡期间未应用计算样式