2013-08-25 73 views
1

下面是我的ajax code.I寫了我的問題,如下面的代碼註釋:鏈路標識類名通過PHP返回外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代碼運行

回答

2

您需要使用事件代表團,您需要使用這裏

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

一個固定的類名,如果類album不固定的,那麼另一種解決方法是將綁定甚至元素T後處理程序創建

$.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"); 
} 
+0

@ Arun您的第一個解決方案,我曾嘗試過最重要的,但它沒有奏效。但你的第二個解決方案措辭謝謝! –

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。