2012-05-02 88 views
0

我有一个从标题创建工具提示的功能。我试图在返回工具提示前检查标题长度的if语句中封装这个函数。但它似乎不想返回任何东西。 if语句有没有更好的方法来做到这一点?来自标题属性的自定义工具提示功能

$(document).ready(function() { 

if ($('#menu-headermenu a').attr('title').length == 0) { 

return null; 

} else { 

//Select all anchor tag with rel set to tooltip 
$('#menu-headermenu a').mouseover(function(e) { 

    //Grab the title attribute's value and assign it to a variable 
    var tip = $(this).attr('title');  

    //Remove the title attribute's to avoid the native tooltip from the browser 
    $(this).attr('title',''); 

    //Append the tooltip template and its value 
    $(this).append('<div id="tooltip"><p>Take me to:<p><div class="tooltipcontent"' + tip + '</div></div>');  

    //Set the X and Y axis of the tooltip 
    $('#tooltip').css('top', e.pageY + 10); 
    $('#tooltip').css('left', e.pageX + 20); 

    //Show the tooltip with faceIn effect 
    $('#tooltip').fadeIn('500'); 
    $('#tooltip').fadeTo('10',0.8); 

}).mousemove(function(e) { 

    //Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse 
    $('#tooltip').css('top', e.pageY + 10); 
    $('#tooltip').css('left', e.pageX + 20); 

}).mouseout(function() { 

    //Put back the title attribute's value 
    $(this).attr('title',$('div.tooltipcontent').html()); 

    //Remove the appended tooltip template 
    $(this).children('div#tooltip').remove(); 

}); 

} 
}); 

回答

2

您是否考虑过使用现有解决方案? (例如http://jquery.bassistance.de/tooltip/demo/

至于你的问题,你可以再补充一个过滤器,以你的选择:$('#menu-headermenu a[title]')

这应该让这个只有具有title属性的元素都将附加的事件。

+1

我喜欢那个选择器过滤器;不会将它添加到我的答案中,因为信用欠额,但也可能与我的方法混在一起。 –

+0

哇,我很抱歉,我首先查看了这个答案。我不太熟悉过滤器。这完全是我所需要的。 非常感谢----你们所有人! – patrick

1

就个人而言,在文档准备就绪后,我会直接绑定我的mouseover函数,而无需进行完整性检查。更灵活,将来如果你添加Ajax调用和类似:

$(document).ready(function() { 
    $('#someWrapper').on('mouseover', '#menu-headermenu a', function(e) { 
    // do stuff 
    }); 
}); 

哪里#someWrapper预计将包含有关的锚链接的任何元素。它不一定是一个带有ID的元素,如果你需要,它甚至可以是'body',尽管通常在大多数文档中可以识别出合适的div。

所有这些都是说“嘿,#someWrapper ...侦听匹配'#menu-headermenu a'的元素上发生的鼠标悬停,是吗?

'if'语句逻辑已经要求您清理DOM以匹配选择器,因此它可能比将事件绑定到#someWrapper更具成本效率。

[更新]

我做的问题错过一部分,但我的回答原来的部分仍然有效......里面的功能,这就是我会做一个全面的检查为标题的存在或标题的空字符串。

var title = $(this).attr('title'); 
if (title !== undefined && title !== "") { /* etc */ } 
+0

是的,我同意,但我希望该功能只有当有一个标题属性创建工具提示时完成。 – patrick

+1

更新了答案。还要注意,你可以将rkw的选择器放到'.on()'函数中,而不是进行完整性检查,它将被过滤以检查标题的* exists *(尽管如此,仍然会选择带空标题的锚) 。 –

1

假设你可以不直接使用[标题] ...

你需要用你的支票,如果在每个语句。

$('#menu-headermenu a').each(function(){ 
    if($(this).attr('title').length === 0){ 
    ... 
    } 
}); 
+0

我喜欢这种类型的解决方案,但它运行我的功能,无论标签属性是否附加到锚标签。 – patrick

+1

然后你可以做$('#menu-headermenu a [title]')。each(...或者我不理解问题:) –