how to properly handle an onclick event in conjunc

2019-02-20 02:59发布

问题:

The following post relates to a previous question I asked here.

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

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.

I have an onlick handler attached to each suggestion.

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

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

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

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

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?

Hope my question makes sense.

回答1:

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).

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.