How the heck is this jQuery selector working?
I am writing a simple tooltip:
$(function() {
$('a').hover(function() {
var curLink = $(this);
var toolTipText = curLink.attr('title');
if (toolTipText)
{
var theOffset = curLink.offset();
$('body').prepend('<div id="toolTip">'+toolTipText+'</div>');
// how the heck is this working???
$('#toolTip').css({
'left' : theOffset.left+'px',
'top' : theOffset.top - 30+'px'
});
}
}, function() {
$('#toolTip').remove();
});
});
As you can see a div with the id of "toolTip" is dynamically added to the DOM when a user开发者_如何学JAVA hovers over a link. That div isn't there initially when the DOM loads but is added later. So I assumed I had to use the live()
function and attach an event to it. But some how it works if I just treat it as a regular selector. Not that I'm complaining but how is this working?
You don't need live because that selector doesn't run before the element is in the DOM.
- OnMouseOver tooltip is added into the DOM.
- Onmouseout that selector runs and tooltip is removed from the DOM. It works fine because by the time the mouseout function is called the tooltip has been added to the DOM already by the mouseover.
You would only need to use 'live()'
if your <a>
element wasn't in the DOM yet when you attach the events. IE. Any anchors added to your page after that code executes won't have tooltips.
It works because you call the .css() function AFTER each time you create the element, so when it fires the element already exists.
精彩评论