2012-12-03 74 views
1

当前我正在为我的网站开发自定义工具提示。这是一个沉重的问题,所以它在每个页面上都有大约300个标题。和它的使用此代码正常工作:具有属性长度的JQuery HasAttribute选择器

var title=""; 
    $(document).delegate("[title]", "mouseover", function (event) { 
     title = $(this).attr("title"); 
     $("#tooltip-div").delay(250).animate({ top: newTop, opacity: 1 }, 'fast'); 
    }); 

但我面临的问题是: 遗憾的是,其中有title属性,但空页的许多元素。例如:

<input type="image" id="clearBtn" title="" src="../../Images/unsearch.png" onclick="clearFilter();"> 

对于此元素,我的自定义工具提示显示为空值。 所以我想知道是否有任何方法来选择具有“标题”属性和属性不为空的元素。

所以我想排除像上面显示的那些元素。有没有办法直接使用JQuery Selector来做到这一点,以确保我只将事件绑定到我期望的元素上,其他方法是检查事件处理函数内部title属性的长度。

在此先感谢。这是我在StackOverflow上的第一个问题。让我知道如果我错过了什么。

回答

4

这是一个可能的解决方案,需要一个[title]和一个[title!='']

var title=""; 
$(document).delegate("[title][title!='']", "mouseover", function (event) { 
    title = $(this).attr("title"); 
    $("#tooltip-div").delay(250).animate({ top: newTop, opacity: 1 }, 'fast'); 
}); 
+0

+1好用!= –

+0

干杯,@Shree - 测试过它,并且'[title]'选择器和'[title!='']'选择器都是必需的。使用'[title!='']选择器将匹配所有没有标题的元素。 –

+0

很棒的回答。谢谢 –

1

以前的解决方案(类似于使用:not selector from CSS 3)是有效的,但它没有考虑以下情况(See example at jsfiddle):

<a href="#" title=' '>anchor 1</a> 
<span title=' '>anchor 2</span> 

所以,如果你想要做的彻底检查标题值,你就可以使用长度和修剪,但使用jquery每个方法:

$('[title]').each(function() { 
    var title = $(this).attr('title').trim(); 
    if (title =! '') { 
    $(this).on("mouseover", function(event) { 
     title = $(this).attr("title"); 
     $("#tooltip-div").delay(250).animate({ top: newTop, opacity: 1 }, 'fast'); 
    }) 
    } 

}); 

另外,还要注意As of jQuery 1.7, delegate method, has been superseded by the .on() method

+0

感谢您的兴趣。但最后的解决方案解决了我的问题。 +1; –