首页 > 解决方案 > 表单提交后如何重定向用户?

问题描述

目标: 将用户在 Elementor 中提交表单后重定向到不同的页面。重定向将基于存储的 javascript 变量。我为提交按钮提供了一个名为submitbutt.

实现: 对于 Elementor 中的表单,我选择了Actions after submitto 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>

问题:用户点击提交按钮后,没有发生重定向。

标签: javascriptwordpressredirectelementor

解决方案


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()


推荐阅读