大佬教程收集整理的这篇文章主要介绍了保持一个函数直到用户在 JavaScript 中提交,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
const onsubmit = ()=>{
someFunction().then(()=>{
// Now wait for user to click on a button
// something very SIMILAR TO prompt()
// user clicked
// do something
})
}
这里基本上用户最初在提交表单时执行一个函数,该函数返回一个承诺,现在 .then() 将等待用户单击另一个按钮,然后将执行其余代码。基本上,他们使用警报/提示的方式在用户不单击确定/取消之前不会执行该功能。唯一的区别是这里不是提示而是另一个按钮
P.S:我正在使用 ReactJs
您可以编写一个返回 Promise 的函数,该函数根据点击确认或取消(或其他)来解决或拒绝,并让您的 onSubmit 处理程序等待该 Promise。
// just getTing references to the dom elements we need so we can
// add listeners and such. necessary here but not really relevant
// to the solution.
document.querySELEctor('form').addEventListener('submit',onSubmit);
const el = document.querySELEctor('.confirm')
const confirmButton = el.querySELEctor('#confirmation');
const cancelButton = el.querySELEctor('#cancel');
async function onSubmit (E) {
// stop the form from submitTing
e.preventDefault();
try {
// await confirmation
await confirmation();
// then do whatever you need to do.
console.log('confirmed');
}
catch (E) {
// confirmation() rejects on cancel,so do whatever
// you need to do (maybe nothing at all) if the user
// clicks cancel.
console.log('canceled');
}
}
function confirmation () {
el.classList.add('visible');
const hide = () => el.classList.remove('visible');
return new Promise((resolve,reject) => {
confirmButton.addEventListener('click',() => { hide(); resolve(); } );
cancelButton.addEventListener('click',() => { hide(); reject(); } );
});
}
.confirm {
display: none;
}
.confirm.visible {
display: block;
}
<form>
<button>Submit</button>
</form>
<div class="confirm">
<button id="confirmation">confirm</button>
<button id="cancel">cancel</button>
</div>
以上是大佬教程为你收集整理的保持一个函数直到用户在 JavaScript 中提交全部内容,希望文章能够帮你解决保持一个函数直到用户在 JavaScript 中提交所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。