2012-05-22 55 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

你可以擴展嗎? –