如何正确处理与 onblur 结合的 onclick 事件 [英] How to properly handle an onclick event in conjunction with an onblur

查看:22
本文介绍了如何正确处理与 onblur 结合的 onclick 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下帖子与我在 这里提出的一个问题有关.

虽然这 2 个问题是独立的,但它们确实与我实现的相同功能有关 - 预测文本.

Although the 2 problems are independent they do relate to the same feature that I implementing - predictive text.

我遇到的问题与 onbluronclick 这两个事件的调用方式有关.

The problem I am running into has to do with how the 2 events onblur and onclick are called.

这种情况发生在用户在文本框中输入了一些字符并决定他们希望点击建议而不是完成输入整个单词之后.

The situation occurs after the user has typed some characters into the text box and decide that they would like to instead click on a suggestion instead of finishing typing the entire word.

我为每个建议附加了一个 onlick 处理程序.

I have an onlick handler attached to each suggestion.

不过,我的文本框还附加了一个 onblur 处理程序.

However, I also have an onblur handler attached to my textbox.

问题在于 onblur 处理程序应该关闭建议框并销毁其内容.

The problem is that the onblur handler is supposed to CLOSE the suggestions box and destroy its contents.

onlick 处理程序需要内容才能复制单击的 div 的值并将其复制到文本框中.

The onlick handler needs the contents in order to copy the value of the clicked div and copy it into the textbox.

因此,进退两难.如果它已被 onblur 处理程序销毁,我将无法复制任何内容.

Hence, the dilemma. I can't copy anything if its already been destroyed by the onblur handler.

如何捕获 onblur 事件,同时判断 onblur 是否是由用户点击"触发的?关于其中一项建议?

How do I trap an onblur event, but also at the same time figure out if the onblur was triggered by the user "clicking" on one of the suggestions?

希望我的问题有意义.

推荐答案

我尝试了许多不同的方法,包括将我的文本输入字段和我的自动填充 div 包装在父 div 中,并在父 div 上设置 onblur - 但没有任何效果.显然,您不能在 div 上分配 onblur 事件(因为它一开始就无法获得焦点).

I tried a number of different things including wrapping both my text entry field and my autoFill div in a parent div and setting the onblur on the parent - but nothing worked. Apparently you cannot assign an onblur event on a div (since it cannot get focus to begin with).

答案是按照 Seth 的建议在 onblur 事件上设置超时.

The answer was to set a Timeout on the onblur event as Seth has suggested.

onblur="setTimeout(function() {closeSuggestionBox();}, 100);"

我在帖子中找到了一个很好的解释 这里.

I found a good explanation of this on a post here.

这篇关于如何正确处理与 onblur 结合的 onclick 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆