jquery 表单提交阻止默认值在移动终端上不起作用

hjzp0vay  于 2023-01-12  发布在  jQuery
关注(0)|答案(1)|浏览(121)

我在表单提交时使用event.preventDefault,它可以正常工作,但只适用于桌面设备。当使用移动终端时,表单以正常方式提交,事件不会被阻止。
下面是我的设置:
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

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

lh80um4z1#

脚本应具有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()
  })
})

测试用例:demo

相关问题