Ajax调用后的数据属性长度检查

时间:2013-12-02 15:00:26

标签: javascript jquery html ajax

我有一些Ajax加载元素。在此之后,我需要在data上阅读这些元素的一些mouseenter属性。但是出了点问题,每个加载的元素都无法显示数据属性。

HTML:

<label data-href="/79" data-tooltip="description" class="tooltip">some label</label>

和一些JS:

var tooltip = $('.tooltip');

tooltip.on({
    mouseenter: function(){
        if ($(this).data('tooltip').length){
            $('body').append('<span class="tooltip_vwr"/>');
        ...

如何在ajax加载后调用lenght方法?谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

试试这个:

$(document).on("mouseover", ".tooltip", function(e){
    //your code here
    if ($(this).data('tooltip').length){
        $('body').append('<span class="tooltip_vwr"/>');
    }
})
如果仅在返回到ajax调用的数据完全加载时绑定此事件,则

会更好。 (现在我不确定是否有更好的方法......先尝试一下) 像:

 //EDIT - remember if this handler will trigger 2 or more time insert .off() before .on()
 var myhandler = function(){
   $(".tooltip").on(function(e){
      //your code here
      if ($(this).data('tooltip').length){
        $('body').append('<span class="tooltip_vwr"/>');
      }
    })
 }
$(function(){

   // call each time u need to rebind
   myhandler();

   $.ajax({
    //ajax option
    success : function(response){ 
       //at the end of your parsing and manipulating function you can bind event
       myhandler();
    }
   });
})

如果你调用ajax 2或更多时间在.on()之前添加一个.off()函数,如:

$(".tooltip").off().on(function...

防止双重绑定。

答案 1 :(得分:1)

尝试使用event delegation,即将事件侦听器绑定到绑定时保证存在的封闭元素。例如:

$(document).on('mouseenter', '.tooltip', function() {
   //...
});

另见: