1

下面是我的 ajax 代码。我在下面的代码中将我的问题写成注释:

//Make the Ajax Request
$.ajax({
    type: "POST",
    url: "dbtryout2_2.php",
    data: datastr,
    success: function(arrayphp) {
         //the problem is with this album class.
         //Its not getting identified outside ajax code
         var link = $('<a href="#" class="album"><font color="red">' + arrayphp + '</font></a>');
        linkclass = link.attr("class"); 
        $(".searchby .searchlist").append(link);   
    }
});
}); 

  //On clicking element of "linkclass" The code below is not working

    $(".searchby .searchlist '.'+linkclass").on("click", function() {
 alert("iam here");
 });

 //while this code is working when i have included directly a span 
 //element "clickme" inside "searchlist division" and have given class name    "democlass" to it
 //On clicking the democlass element alert function is gettting called

     //i want alert function to be called for above code also
 $(".searchby .searchlist .democlass").on("click", function() {
 alert("iam here");
});

我希望 ajax 代码之后的代码运行

4

2 回答 2

2

需要使用事件委托,这里需要使用固定的类名

$('.searchby .searchlist').on('click', '.album', function() {
    alert("iam here");
});

如果类album不固定,则另一种解决方案是在创建元素后绑定事件处理程序

$.ajax({
    type: "POST",
    url: "dbtryout2_2.php",
    data: datastr,
    success: function(arrayphp) {
        var link = $('<a href="#" class="album"><font color="red">' + arrayphp + '</font></a>');
        link.click(albumClickHandler)
        $(".searchby .searchlist").append(link);   
    }
});

function albumClickHandler() {
    alert("iam here");
}
于 2013-08-25T12:40:18.533 回答
0

您需要在 ajax 回调中绑定您的点击处理程序,如下所示:

$.ajax({
    type: "POST",
    url: "dbtryout2_2.php",
    data: datastr,
    success: function(arrayphp) {
        //the problem is with this album class.
        //Its not getting identified outside ajax code
        var link = $('<a href="#" class="album"><font color="red">' + arrayphp + '</font></a>');
        linkclass = link.attr("class"); 
        $(".searchby .searchlist").append(link);   

        $(".searchby .searchlist '.'+linkclass").on("click", function() {
            alert("iam here");
        });
    }
});
}); 

这样,在您将链接添加到 DOM 后,就会立即绑定 click 事件。

于 2013-08-25T12:42:42.580 回答