2016-12-17 13 views
-1

我们有以下脚本,当页面第一次加载时,我们呼叫FindPromo()此功能特别等待HTML Table的子代加载。Jquery函数仅适用于页面加载,在AJAx加载数据后无法运行

然后,它查找所有td's与类.promotion,并在同一时间检查,以确保td目前在用户观看通过调用checkvisible如果是那么我们分配额外promoSelect它,我们也把这个当用户滚动浏览表格,如果他们滚动并看到类别为promotiontd,我们再次将promoSelect分配给它。

我们再调用GetPromo这个循环中的table发现有类promoSelect和检索td's是从它的值 - 到目前为止,这工作完全正常。

问题:

在表的顶部,有4 buttons,4 buttons允许user加载它通过AJAX做不同的数据,这又再次填充html表,当user按一个buttons我连线了一个点击事件再次呼叫FindPromo(),但它似乎并没有将promoSelect类附加到任何td's具有类.promotion类数据已成功加载后,即使我已检查td's我可以看到几个哈等级.promotion

现在我已经放在console.logsFindPromo()/GetPromo()他们似乎写到控制台,但是脚本失败后user推动了4个按钮中的一个运行。

脚本:

// Called on page load and when the user clicks on 1 of the four buttons 
function FindPromo() { 

var checkExist = setInterval(function() { 

var length = $('table.tst-orderProductsTable').find('tbody').children().length; 

if (length > 0) { 

    clearInterval(checkExist); 

    $('tbody').scroll(function() { 
    $('.promotion').filter(checkVisible).addClass('promoSelect'); // Find all promotion td's and assign promoSelect class to them 
    GetPromo(); 
    }).scroll(); 

} 
}, 500); 
} 

function checkVisible() { 
    var elm = this; 
    var eval = eval || "visible"; 
    var vpH = $(window).height(), // Viewport Height 
    st = $(window).scrollTop(), // Scroll Top 
    y = $(elm).offset().top, 
    elementHeight = $(elm).height(); 

    if (eval == "visible") return ((y < (vpH + st)) && (y > (st - elementHeight))); 
} 


// Now loop the td's and find all td's that have the class promoSelect. 
// Then retrieve information from that td 
function GetPromo() { 

var product_description = ''; 
var product_position = ''; 

$("td").each(function (i, row) { 

    if ($(this).hasClass('promoSelect')) { 
     console.log("here"); 
    } 

}); 
} 


// clicking 1 of the four buttons above table. 
$('.product-tab-label').click(function() { 

    FindPromo(); 

}); 

FindPromo(); 
+0

究竟你通过表示“无法运行”?控制台上是否有错误?当你调试时,调用函数时会发生什么?它具体如何失败? – David

+0

@David当我说运行失败时,在用户按下四个按钮之一后,它没有找到所有类别提升的td。然而,在页面加载时,它工作得很好。 –

+0

因此,在回调'.scroll()'选择器'$('。promotion')'时不会返回匹配的元素?这强烈暗示当时页面上不存在这样的元素。它们是以某种方式被动态修改或从DOM中卸载/重新加载的? – David

回答

0

当安装事件的元素,你可以使用一个直接的方法或委托的方式。这里是直接的样子:

$('.product-tab-label').click(function() { 

    FindPromo(); 

}); 

在这里,每个.product-tab标签已经单独给出说明。如果新的.product-tab-label被创建[这是DOM更改时发生的情况],这些新元素没有任何指令,并且不会响应点击[和随后的FindPromo();将'不能运行']。 每个.product-tab-label是直接负责自己的事件。

由于您希望指令能够在DOM更改中生存下来,因此您需要使用委派的事件。

$(".product-tab-label-parent").on("click", ,".product-tab-label" ,function() { 
    FindPromo(); 
}); 

在这种情况下,指令给父元素(。产品标签 - 标签父),当他们改变其附着的事件,它的孩子甚至。

有直接和委托的事件在这里的一段:https://api.jquery.com/on/

由您所示的代码去,我想这table.tst-orderProductsTable是一个合适的父元素。使用此:

$("table.tst-orderProductsTable").on("click", ,".product-tab-label" ,function() { 
    FindPromo(); 
}); 
相关问题