如何通过 ID 修复表单上的错误设置键事件?

How to fix error setting key event on form by its ID?

我想将 google 地图添加到我的 Laravel 8 / tailwindcss 2 / Alpinejs 2.8 应用程序中 我找到了例子 https://laraveldaily.com/laravel-find-addresses-with-coordinates-via-google-maps-api/

因为我不使用 jquery,但是 alpinejs 我得到了一个错误:

alpine.js:115 Alpine Error: "TypeError: form_ad_location_edit.on is not a function"

当我尝试重新编写代码时:

$('form').on('keyup keypress', 函数(e) { var keyCode = e.keyCode || e.which; 如果(键码=== 13){ e.preventDefault(); return 错误; } });

进入:

<form action="{{ route('admin.ads.ad_locations.'. ( $isInsert ? 'store' : 'update'), [1, ( $adLocation->id ?? '' ), 1 ] ) }}" method="POST" id="form_ad_location_edit" enctype="multipart/form-data">

let form_ad_location_edit = document.querySelector("#form_ad_location_edit")
console.log('form_ad_location_edit::')
console.log(form_ad_location_edit)

form_ad_location_edit.on('keyup keypress', function(e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode === 13) {
        e.preventDefault();
        return false;
    }
});

在控制台中我看到我得到了有效的表单元素?

哪种方式有效?

谢谢!

我找到了使用 addEventListener 方法的决定:

let form_ad_location_edit = document.querySelector("#form_ad_location_edit")
adLocationLng= parseFloat(adLocationLng)
adLocationLat= parseFloat(adLocationLat)
form_ad_location_edit.addEventListener("keyup keypress", function(e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode === 13) {
        e.preventDefault();
        return false;
    }
});

这对我有用。