问题
document.addEventListener("click", function (e) {
var filter = document.getElementById('filter');
if (e.target !== filter[0]) {
filter.blur();
}
});
My attempt ^^
jQuery Code:
$(document).on('click', function(e) {
if (e.target !== $('#filter')[0])
$('#filter').blur();
});
When any element except #filter is clicked I would like to blur (unfocus) #filter
回答1:
You don't need to dereference the result of getElementById
with the [0]
- the result is already a single element.
The [0]
is only necessary in jQuery because jQuery results are always pseudo-arrays even if there's only one matching element.
Given this function is being called for every single click on the page, consider moving the definition of filter
outside of the function so that you don't have to re-evaluate it for every click (assuming that the element is static).
来源:https://stackoverflow.com/questions/24300118/blurunfocus-an-element-when-other-element-is-clicked