【问题标题】:Keypress in text input preventing typing文本输入中的按键阻止输入
【发布时间】:2016-09-22 18:44:07
【问题描述】:

我有一个文本输入,我想在按下 enter 时执行一个函数。我使用 if 条件来确定是否按下了输入,但这会导致用户无法在输入框中输入。我可以在 else 条件中放置什么以允许他们正常输入?

JsFiddle

function addItem(e) {   
    e.preventDefault();                         // Prevent form being submitted
    var text = $('input:text').val();           // Get value of text input
    var itemArr = text.split(',');                                                              
    var lngth = itemArr.length                  

    for(i = 0; i < lngth; i++)                  
    {
        $list.append('<li>' + itemArr[i] + '</li>');    // Add item to end of the list
        updateCount();                                  // Update the count
    } // End loop

    $('#addItems').val('');                         // Empty the text input
    return false;
}

$('#addItems').keypress(function(e) {
    if(e.which == 13) {
        addItem();
    }
    return false;
});

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    从按键功能中删除return false;

    $('#addItems').keypress(function(e) {
        if(e.which == 13) {
            addItem();
        }   
        else {
            return true;
        }
    
        return false;   
    });
    

    【讨论】:

    • 如果我这样做,当我按下回车键时页面会刷新,这是我不想要的
    • @Shniper 然后使用 else 并返回 true
    • 当我按下回车时仍然刷新,你的代码
    • 用这个代替
    【解决方案2】:

    Jusr remove 从按键事件中返回 false

    你可以看到这个Question

    return false; 如果在 HTML 中的事件处理程序属性末尾调用,则成功取消跨浏览器的事件。

    为了防止表单被提交,您可以在表单中添加 onsubmit="return false"

    Demo

    【讨论】:

    • @Shniper 我认为这可以解决您的表单提交问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    相关资源
    最近更新 更多