单击始终首先ajax调用

时间:2014-08-28 23:01:38

标签: jquery ajax

我正在尝试通过三个步骤创建一个带有框的页面,并且每个步骤都需要由ajax加载,每次单击按钮“next”后步骤都会更改。 我正在改变每一步按钮的类,所以我可以加载下一个,不知道是否有更好的方法。但当我点击进入第二步时,第一步就是我。

     /**** THIS WORK FINE *****/
    // First Click on Next Button load first step

    $('.next-button').on('click', function(){
        $('.first-step').load('includes/selecione-torcida.html');
        $('.next-button').addClass('next-torcida');
    });

   /**** THIS DON'T WORK *****/
   // Second Click on Next Button load second step but in the class "next-torcida"

   $('.next-torcida').on('click', function(){
     $('.first-step').load('includes/selecione-amigos.html');
   });

1 个答案:

答案 0 :(得分:2)

这是直接事件处理程序的一个示例,它只会应用于DOM创建点上的元素。

你需要使用delegated event handler,因此它会冒泡到新添加的元素(或者在这种情况下,你要分配的类然后想要绑定到点击。

以下是如何使用委托进行的示例:

// Direct event, is only bound to elements existing at DOM creation point
$('.next-button').on('click', function(){
    $('.first-step').load('includes/selecione-torcida.html');
    $('.next-button').addClass('next-torcida');
});

// Delegated event, will listen for newly created elements too
$(document).on('click', '.next-torcida', function(){
    $('.first-step').load('includes/selecione-amigos.html');
});

基本上,你告诉jQuery要监听整个文档中存在的所有.next-torcida元素的点击,其中包括所有新创建的元素。

直接的方式是,当加载DOM时,事件处理程序将单独附加到具有.next-button类的每个元素,因此创建的新元素将不具有处理程序,您必须绑定创建它时的新事件处理程序。

注意:我刚刚在这里使用document作为一个例子,这是非常广泛的,因为性能原因将其缩小到最接近的父亲是一个好主意这些元素分享。

Here's another post解释直接与委派之间的差异。