jQuery:删除浏览器生成的 title 属性

jQuery: Removing Browser Generated Title Attribute

本文关键字:title 属性 删除 浏览器 jQuery      更新时间:2023-09-26

我正在尝试删除浏览器生成的标题框,该框与具有标题属性的锚点一起出现。我想这样做的原因是它不会干扰我的工具提示jQuery。

截至目前,我正在悬停时删除标题属性,但在将自己从悬停状态中删除后,它不会重新分配它。怎么来了?

http://jsfiddle.net/fj4xz/5/

那是因为

var title

在 HandlerIn 函数中,而不是在处理程序 out 中定义。最简单的解决方案是将 de var title 放在悬停函数之外,并将其分配给悬停处理程序中。

编辑:删除Photon所述的变量也是一种解决方案。不过,我强烈建议您使用变量。如果未定义全局变量,您的代码很快就会变得混乱且无法维护。但这只是我的意见。

http://jsfiddle.net/RubenJonker/fj4xz/6/

这是因为您的title变量在mouseenter函数中,但您在mouseleave 中使用它。应将title变量移到 hover 方法之外。

var title;
$('a.tooltip').hover(function() {
    title = $(this).attr('title');
    var offset = $(this).offset();
    var width = $(this).outerWidth();
    var height = $(this).outerHeight();
    $content = $('<div class="tooltip">' + title + '</div>').fadeIn('fast');
    $(this).append($content);
    $(this).attr('title', '');
    $content.offset({
        top: offset.top + height,
        left: offset.left + (width - $content.outerWidth()) / 2
    });
}, function() {
    $(this).find('div').fadeOut('fast');
    $(this).attr('title', title);
});​

它不会重新分配标题值的原因是,您在第一个函数中声明了 title 变量,这超出了第二个函数的范围。如果要保留原始标题值,则需要以第二个函数可以访问它的方式执行此操作。

相反,请尝试将其添加到数据值:

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

然后在第二个函数中重新分配它:

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

我会避免有一个通用的title变量漂浮在你正在设置和获取页面上的n个链接。对我来说,将值存储为元素本身的数据似乎是一种更好的方法。

你在第一个函数中声明var title = $(this).attr('title');,但你的第二个函数不知道title

只需删除变量名之前的所有var声明

它将成为全局变量 看到这个

  $('a.tooltip').hover(function() {
        title = $(this).attr('title');
         offset = $(this).offset();
         width = $(this).outerWidth();
         height = $(this).outerHeight();
        $content = $('<div class="tooltip">' + title + '</div>').fadeIn('fast');
        $(this).append($content);
        $(this).attr('title', '');
        $content.offset({ top: offset.top+height, left: offset.left+(width-$content.outerWidth())/2 });
    }, function() {
        $(this).find('div').fadeOut('fast');
        $(this).attr('title', title);
    });​