javascript - 表单提交后如何重定向用户?
问题描述
目标:
将用户在 Elementor 中提交表单后重定向到不同的页面。重定向将基于存储的 javascript 变量。我为提交按钮提供了一个名为submitbutt
.
实现:
对于 Elementor 中的表单,我选择了Actions after submit
to Redirect
。同样在该 Redirect
部分中,我选择了该to Shortcode
选项并参考了我的简码[elementor-template id="1343"]
。
简码
它是一个包含 javascript 的 HTML,它看起来像这样。
<script type="text/javascript">
document.getElementById('submitbutt').onclick = function() {
if (localStorage.getItem('pagex') === 'page_1') {
window.location = 'https://www.website.com/error/?1';
}
else if (localStorage.getItem('pagex') === 'page_2') {
window.location = 'https://www.website.com/error/?2';
}
else {
window.location = 'https://www.website.com/error/';
}
};
</script>
问题:用户点击提交按钮后,没有发生重定向。
解决方案
document.getElementById('submitbutt').addEventListener("click", function(event) {
event.preventDefault();
if (localStorage.getItem('pagex') === 'page_1') {
window.location = 'https://www.website.com/error/?1';
}
else if (localStorage.getItem('pagex') === 'page_2') {
window.location = 'https://www.website.com/error/?2';
}
else {
window.location = 'https://www.website.com/error/';
}
});
使用带有按钮的事件处理程序
对于表单,要自定义按钮的行为,请使用event.preventDefault()
推荐阅读
- javascript - 如何根据文本框值动态访问 javascript 对象的属性?
- java - Map Reduce 数组越界异常
- kubernetes - 无法公开 Kubernetes 仪表板以从外部访问它
- javascript - 为什么警报换行符不起作用?
- python - 在 Django PostgreSQL 中排序太慢了
- java - org.osgi.framework.BundleException:无法解析模块:org.eclipse.jetty.plus
- java - 确定输入字符串是否确实是有效的四字符双精度字面量
- apache-spark - 使用 Spark Structured Streaming 从目录读取内容时如何实现一次性处理?
- wordpress - 古腾堡和经典编辑器 - 如何在经典编辑器中使用自定义古腾堡块?
- flutter - 在颤动中检测“输入键”按下