问题
I am trying to make a search box with an auto-suggest panel that comes down if the user clicks on the search box once it already has focus. I have tried checking $("#search_box").is(":focus"), and using the following code, both of which had the same problem:
var fade_in=function() {
$("#search_panel").fadeIn(100);
};
$(document).ready(function() {
$("#search_panel").fadeOut(100);
$("#search_box").focus(function() {
$(this).on("click", fade_in);
});
$("#search_box").blur(function() {
$(this).off("click", fade_in);
$("#search_panel").fadeOut(100);
});
});
it seems that the order of the events makes it so that the search panel always comes up on the first click - the order is:
- the user clicks the search box
- it comes into focus
- the click handler is added
- and then the click event fires causing the panel to appear
whereas I was hoping it would be:
- the user clicks the search box
- the click event is fired
- the box comes into focus, so the click handler is added
- nothing happens yet, as the handler wasn't added when the click event occurred.
On the second click, the panel should appear as the input box will already have focus.
Here is the current code: http://jsfiddle.net/DtfYq/
回答1:
If I've understood you correctly, I believe the following code should do what you're after:
var toggle=function() {
$("#search_panel").fadeIn(100);
};
$(document).ready(function() {
$("#search_panel").fadeOut(100);
$("#search_box").on("click", function() {
if ($(this).is(':focus')) {
$(this).on("click", toggle);
} else {
$(this).focus();
}
});
$("#search_box").blur(function() {
$(this).off("click", toggle);
$("#search_panel").fadeOut(100);
});
});
Revised JSFiddle:
I've amended it so that when the search box is clicked, it checks to see if that element has focus. If it does, it attaches the click
event. Otherwise, it just focuses on it.
来源:https://stackoverflow.com/questions/18548626/jquery-do-something-if-text-input-clicked-when-it-already-has-focus