在提交表单上按回车

Pressing enter on submit form

为什么当我按下 enter 时它没有 运行 code,因为我把应该 运行 的代码放在了 if statement 中。 当我按 enterconsole log 它不 运行 它正确。

document.getElementById('city-location').addEventListener('keyup', (e) => {
    const LOCATION = document.getElementById('city-location').value
    if(e.target.which == 13 || e.target.keyCode == 13) {
        weatherApi.changeLocation(LOCATION);
        storage.setStorage(LOCATION);
        getWeatherApi();
    } else {
        console.log('Wrong key pressed');
    }

    e.preventDefault();
})

这是标记:

<form id="weather-modal-form">
 <div class="form-group">
    <label for="city">City</label>
    <input type="text" id="city-location">
 </div>
</form>

您应该为输入按钮添加 submit 事件。

document.getElementById('weather-modal-form').addEventListener('submit', (e) => {
    e.preventDefault();
    console.log("work's");
})
<form id="weather-modal-form">
 <div class="form-group">
    <label for="city">City</label>
    <input type="text" id="city-location">
 </div>
</form>