How to bind a blur event to a live click event?
I have this function:
$('input#auto_results').bind('blur', function(e) {
$('.result').bind('click', function() {
return;
});
$('#results_container').hide();
});
Basically, I would like the #results_container to hide on blur UNLESS an element with the class .res开发者_如何学JAVAult is clicked.
The above function does not work
Problem with your code:
What you're trying to do, is attaching a click
event handler on .result
in the event handler of another event (blur
).
Your code will do nothing except attaching this click
handler that basically does nothing.
Simple option:
The blur
event will be triggered first, and the click
on .results
second, so this is not an easy situation.
The simplest way you can do this is:
$('input#auto_results').blur(function () {
$('#results_container').hide();
});
$('.result').click(function () {
$('#results_container').show();
});
jsFiddle Demo
So just hiding the container, an on click, show it again. Results in a small blink.
Timeout option:
Another option I can think of, is setting a small timeout when the blur
is triggered, and on the click event of .results
, cancel it. In this example, I store the timeout on body
with the .data()
function, you could store it on a more logical element, this is just a demonstration:
$('input#auto_results').blur(function () {
var cucc=setTimeout(function () {
$('#results_container').hide();
$('body').removeData('blurTimeout');
}, 100);
$('body').data('blurTimeout', cucc);
});
$('.result').click(function () {
var cucc=$('body').data('blurTimeout');
if (typeof cucc != 'undefined') {
clearTimeout(cucc);
}
});
jsFiddle Demo
精彩评论