简体   繁体   English

表单提交 preventDefault 不适用于移动设备

[英]Form submit preventDefault not working on mobile device

I'm using event.preventDefault on a form submission and it works, but only on desktop devices.我在表单提交上使用 event.preventDefault 并且它有效,但仅适用于桌面设备。 When using a mobile device the form is submitted the normal way and the event is not prevented.使用移动设备时,表单以正常方式提交,事件不会被阻止。

Here's what my setup looks like:这是我的设置的样子:

index.html index.html

<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"
        integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm">
   <input id="name">
   <button type="submit">
</form>
</body>
<script src="script.js"></script>

script.js脚本.js

$(function() {
    $("#myForm").submit(function (event) {
        event.preventDefault();
        let formData = $("#name").val();
        console.log(formData);
});

The script should have the body tag.脚本应该有 body 标签。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.6.3.min.js"
        integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
</head>

<body>
    <form id="myForm">
        <input id="name">
        <button type="submit">submit</button>
    </form>


    <script src="script.js"></script>
</body>

</html>

script.js

$(document).ready(function () {
  $(document).on("submit", "#myForm", function (e) {
    e.preventDefault();
    let formData = $("#name").val();
    console.log(formData);
    e.target.reset()
  })
})

Test Case here: demo测试用例在这里:演示

This was related to a project hosted using GitPages.这与使用 GitPages 托管的项目有关。 It turns out that the cause of the problem was that I was trying to reference a script from outside the folder the page was hosted from.事实证明,问题的原因是我试图从托管页面的文件夹外部引用脚本。 The page was hosted from docs/index.html, and I was trying to reference the script using../dist/script.js该页面由 docs/index.html 托管,我试图使用 ../dist/script.js 引用脚本

While looking into it more, I stumbled upon this question which says GitPages doesn't allow that since technically only everything in the docs folder is hosted and the dist folder didn't exist.在深入研究时,我偶然发现了这个问题,它说 GitPages 不允许这样做,因为从技术上讲,只有 docs 文件夹中的所有内容都被托管,而 dist 文件夹不存在。 Not sure why it worked only on my computer...不知道为什么它只适用于我的电脑......

I updated my reference to the script to its jsDelivr URL and everything now works as expected.我将对脚本的引用更新为它的 jsDelivr URL,现在一切都按预期工作。

Thank you to everyone who offered help!感谢所有提供帮助的人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM