jquery:隐藏title属性但不删除它

我已经看到大多数人都会用这个解决方案做到这一点,在鼠标hover时,我们将获取TITLE属性中的值,然后删除它的值。 在鼠标移出时,我们会重新启用它。

$(this).attr('title',''); 

要么

 $(this).removeAttr('title'); 

我想知道是否可以隐藏工具提示而不是删除title属性?

谢谢!

不,你不能,因为浏览器将决定如何处理title属性。 但是,您可以将其与节点一起保存以供以后参考(并可能还原标题):

 $(this).data("title", $(this).attr("title")).removeAttr("title"); 

这很有效。

  $(document).ready(function(){ $( "a" ) .mouseenter(function() { var title = $(this).attr("title"); $(this).attr("tmp_title", title); $(this).attr("title",""); }) .mouseleave(function() { var title = $(this).attr("tmp_title"); $(this).attr("title", title); }) .click(function() { var title = $(this).attr("tmp_title"); $(this).attr("title", title); }); }); }); 

当鼠标hover在元素上时,您可以将标题存储在其他位置。 但是,您不必将其存储在DOM本身中; 你可以将它保存在JS var中:

 (function(){ var ttext; $(yourtargetselectorhere).hover(function(){ ttext = $(this).attr('title'); $(this).removeAttr('title'); }, function(){ $(this).attr('title', ttext); }); }()); 

谢谢你的解决方案。 我在一个项目中遇到了同样的问题。 问题是当我hover图像并且我需要弹出标题时出现一个长丑陋的标题,因为在title属性中,我放置了一个产品的购买链接。 但正如我所说,包含标签的长标题也出现在hover上。 所以我只是在解决方案的末尾添加了一个.click函数,我不知道是否有可能以更加语义的方式解决这个问题,因为我不是一个jquery专家。 完整的脚本粘贴在下面,问候:)

  $(".collection-box a").hover(function(){ // Get the current title var title = $(this).attr("title"); // Store it in a temporary attribute $(this).attr("tmp_title", title); // Set the title to nothing so we don't see the tooltips $(this).attr("title",""); }, function() { // Fired when we leave the element // Retrieve the title from the temporary attribute var title = $(this).attr("tmp_title"); // Return the title to what it was $(this).attr("title", title); }); //Restore the title on click $(".collection-box a").click(function(){ // Retrieve the title from the temporary attribute var title = $(this).attr("tmp_title"); // Return the title to what it was $(this).attr("title", title); }); 

怕你不能。 preventDefault()方法似乎不适用于此,这是不幸的,因为它是理想的。

如果你真的需要保留title属性,你可以这样做:

 $(document).ready(function(){ $("a").hover(function(){ // Get the current title var title = $(this).attr("title"); // Store it in a temporary attribute $(this).attr("tmp_title", title); // Set the title to nothing so we don't see the tooltips $(this).attr("title",""); }, function() { // Fired when we leave the element // Retrieve the title from the temporary attribute var title = $(this).attr("tmp_title"); // Return the title to what it was $(this).attr("title", title); }); }); 

虽然这很复杂。 除非有特定原因需要保留标题属性,否则我会删除它们。

这是一个很好的解决方案,将一个新属性命名为’fancytitle’代替通常的’title’

  Visit Google Search  

并像这样在mouseenter / hover上使用jquery选择属性的值

 $('a#demo').attr('fancytitle')