【问题标题】:Pressing enter on submit form在提交表单上按 Enter
【发布时间】:2019-06-20 06:41:56
【问题描述】:

为什么当我按下回车键时它不运行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>

【问题讨论】:

    标签: javascript forms events submit


    【解决方案1】:

    您应该为输入按钮添加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>

    【讨论】:

    • 我想在输入时直接按 Enter 提交表单。我不想要任何按钮。
    • @Grecdev 更新我的 sn-p 签出。工作没有任何按钮。
    • 好的,但是现在当我按下enter 键时它工作得非常好,但它运行else statement 代码。为什么会这样?
    • 因为您的侦听器是在表单上设置的,而不是在输入字段中。您的 else 语句控制按下的键,并且表单没有此信息:e.target.which 和 e.target.keyCode 是 undefined) 所以 if 是 false。只需将您的代码放在console.log("work's") 之前,它应该可以工作。
    猜你喜欢
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    相关资源
    最近更新 更多