2013-04-10 96 views
0

我正在使用一些ajax來調用一個返回一些html(一個圖像和幾個按鈕)的php文件,然後將其內容放入div中。麻煩的是,我希望能夠使用從PHP返回的按鈕之一的id掛鉤事件處理程序。源的輸出,如果我做的瀏覽器查看源文件只是顯示了HTML注入,而不是HTML的DIV:ajax將html注入div但保留html元素包括它們的ID

<div class="displaysomething"></div> 

我的AJAX如下:

$(document).ready(function() { 
    getServiceDisplay(); 
    $('#stop-service').click(function(e) 
    { 
     e.preventDefault(); 
     runHDIMService(); 
    }); 

}

function getServiceDisplay(){ 
$.ajax(
{ 
    url: 'includes/dosomething.php', 
    type: 'POST', 
    success: function(strOutput) 
    { 
     $(".displaysomething").html(strOutput); 
     }    
    }); 
}; 

PHP - 最終返回一個按鈕,其他的東西。這是我需要根據其id來連接到事件處理程序的。

echo '<input id="stop-service" type="button" value="Run" class="'.$strRunActionButtonClass.'"/>'; 

如果我只是把網頁上的按鈕,而無需使用AJAX進入我的按鈕聯播代碼的偉大工程的股利將其注入。

有沒有人有任何想法?

由於

回答

1

在jQuery中,加入的事件處理程序只將事件添加到現有元件的.click(...方法。不包括以後添加的新元素。

您可以使用事件綁定的jQuery on方法來包含稍後添加的元素。

$("body").on("click", "#stop-service", function(e){ 
    e.preventDefault(); 
    runHDIMService(); 
}); 

我創建了一個simple example on JSFiddle

+0

這偉大工程!我一直在思考這些問題,但是打算進行等待/睡眠,這可能不會奏效,而且非常粗糙。非常感謝您花時間幫助我。 – Yos 2013-04-10 14:52:16

0

的問題是,

$(document).ready(function() { 
    getServiceDisplay(); 
    $('#stop-service').click(function(e) // this doesn't exists yet 
    { 
     e.preventDefault(); 
     runHDIMService(); 
    }); 

這應該工作:

功能getServiceDisplay(){

$.ajax(
{ 
    url: 'includes/dosomething.php', 
    type: 'POST', 
    success: function(strOutput) 
    { 
     $(".displaysomething").html(strOutput); 
     // so after you attached the div from ajax call just register your event 
     $('#stop-service').click(function(e) 
     { 
      e.preventDefault(); 
      runHDIMService(); 
     });    
    }); 
}; 
+0

感謝所有好的建議! – Yos 2013-04-10 15:03:29