2012-05-22 54 views
6

我有一个函数为特定对象创建一个工具提示。目前,我在ajax插入之后运行一个工具提示函数来创建和附加新的工具提示对象。我很好奇,如果有一种方法可以使用.on()在插入时自动运行工具提示功能,而不是手动运行它。JQuery - 使用.on和元素插入

例如:

$('[title]').on('inserted', function(){ 
    tooltip(this); 
}); 

我做了一些阅读,它看起来像自定义触发可能是要走的路,但我很乐意,如果这样的事情存在:)

回答

1

这里的码作为每个请求。

$(document).ready(function() { 
    $('body').on('added','*',function() { 
     console.log($(this),'has been added'); 
    }); 
    $('body').append('<div>This is the first div</div>'); 
}); 

(function($) { 
    fncs = { 
     append:$.fn.append, 
     appendTo:$.fn.appendTo 
     // etc. 
    } 
    // we're assigning the original functions in this 
    // object to be executed (applied) later 
    $.fn.append = function() { 
     fncs.append.apply(this,arguments); 
     $(this).children().last().trigger('added'); 
     return $(this); 
    } 
    $.fn.appendTo = function() { 
     fncs.appendTo.apply(this,arguments); 
     return $(this); 
     // no need to trigger because this function calls the one 
     // above for some reason, and it's taking care of the 
     // triggering the right element(s I think) 
    } 
})(jQuery); 
+0

很好的解决方案。这将是非常棒的,如果它是将来内置到jquery中的东西,但现在会做。谢谢! –

+0

您可能想要浏览http://api.jquery.com/category/manipulation/中DOM操作的所有函数列表。我希望在功能发布中也有一个实现。 – inhan

0

这是不是您要查找的响应,但我不会直接在元素上附加工具提示。相反,我会用一个类我想要的工具提示显示在鼠标悬停并通过以下方式使用.on()事件处理程序中的:

$('body').on('mouseover','.tooltip',function() { 
    // show tooltip 
    console.log($(this).data('tooltip')); 
    return false; 
}).on('mouseout','.tooltip',function() { 
    // hide tooltip 
    return false; 
}); 

所以,无论你增加身体(不一定是直接子)会触发这个事件处理程序。

我可能会创建一个额外的函数,以将工具提示数据与类一起分配给每个元素。

$.fn.extend({ 
    tooltip:function(text) { 
     text = text || ''; 
     return $(this).each(function() { 
      $(this).data('tooltip',text).addClass('tooltip'); 
     }); 
    } 
}); 

$('#someID').tooltip("Click me!"); 
$('button').tooltip("I'm a button"); 
+0

好主意,但是没有真正的答案,我正在寻找。工具提示只是一个例子,我经常遇到这个问题,并且很好奇是否有一个好的解决方案。 :) –

+0

你有没有考虑重写操作函数,并触发一个自定义事件处理程序,如“添加”? – inhan

+0

你可以扩展吗? –