在JavaScript中基于用户输入样式调用不同的事件



我有一个div,它包含一个输入元素来输入一些值。在按enter键或onFocusOut事件时,这些值作为列表元素添加到div的上方。到目前为止,还不错。但是,如果用户键入一些值,没有按回车键,直接点击保存按钮,则不应该调用div对应的onFocusOut函数。相反,它应该接受该类型的值并调用某个save函数。你对如何检测有什么建议吗?

我的代码片段在这里:

JS:

 divInput.onkeypress = function (event){
                return someTestFunc();
    }
    
    
    divInput.tabIndex="-1";
    $(divInput).focusout(function (e) {
        if ($(this).find(e.relatedTarget).length == 0) {
            addToList();
        }
    });

这不是一个非常微妙的解决方案,但您可以在将项目添加到列表之前使用setTimeout,并在保存时清除setTimeout。按钮点击。试试这个:

var $saveButton = $('#exampleButton')[0],
    $divInput = $('#exampleInput')[0],
    timedEvent = -1;
$($saveButton).on('click', function(event){
    if(timedEvent) {
        clearTimeout(timedEvent)
    }
    alert('not add to list & save');
})

$divInput.tabIndex="-1";
$($divInput).on('focusout', function(e) {
    timedEvent = window.setTimeout(function() {
        if ($(this).find(e.relatedTarget).length == 0) {
            alert('add to list');
        }
    }, 200);
});

检查这个工作小提琴

最新更新