Can a jQuery UI datepicker be matched to a click event's target?

半世苍凉 提交于 2019-12-06 06:33:09

问题


I've written a simple jQuery (1.4.2) UI (1.8) widget that embeds a jQuery UI datepicker. I'd like to detect when a user clicks outside my widget, in which case it should automatically hide itself. My code looks roughly like this:

var self = this;
$(document).bind("click.mywidget": function(event) {
    var target = event.target;
    if (!self.container.has(target).length && target != self.container.get(0)) {
        self.hide();
    }
});

The problem comes when clicking on a date or month prev/next button in the datepicker. For some reason, even though Firebug shows those elements as being descendants of my container, the has() check fails for them.

What is happening, and how might I fix this?


回答1:


After digging through the datepicker source a bit, I realized what was going on. Apparently whenever you click on a date, or cycle through months, it empties the entire div and re-creates it.

Since the picker is further down in the DOM, it handles the click event first. By the time the document handler gets called, the target element is no longer in the DOM, and is therefore no longer a descendant of the container.

My hasty hack was to check the target's more direct parents, to see whether any of them is a datepicker table or header. Since this widget is thus far my only use of datepicker, I can assume that a click on such an element should not count as a click outside the container.

I'll update this answer once I come up with a real solution.



来源:https://stackoverflow.com/questions/3570453/can-a-jquery-ui-datepicker-be-matched-to-a-click-events-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!