2016-08-22 18 views
0

請在我瘋了之前幫助我。 好吧,所以我一直在爲我的代碼苦苦掙扎了一週,但我仍然不知道什麼是不工作的。jQuery Ajax加載html數據正常,但屬性似乎'不可讀'

我可以使用錨標記的data-target屬性調用模態。我知道它工作正常。這是我的PHP文件。這也沒有問題。

PHP(放置-load.php)

<?php 
include 'connection.php'; 
$sql = "SELECT * FROM tbl_personal"; 
$r = mysqli_query($con,$sql); 
$nr = mysqli_num_rows($r); 
if($nr > 0) { 
    while($dt = mysqli_fetch_array($r)){ 
     echo " 
      <tr> 
       <td>".$dt[0]."</td> 
       <td><a data-target='#modalShowDetails'>Edit</a></td> 
      </tr> 
     "; 
    } 
}else { 
    echo ""; 
} 
?> 

我有兩個場景 如果我這樣做:

<div class="table"> 
    <table> 
     <thead> 
      <tr> 
       <th>Name</th> 
       <th></th> 
      </tr> 
     </thead> 
     <tbody id="placement-table"> 
      <?php include 'placement-load.php'; ?> 
     </tbody> 
    </table> 
</div> 

表體將​​加載就好了,如果我點擊編輯(在錨標籤中),模態也會加載。

但是!

如果刪除了包括在TBODY標籤,這樣做,(使用jQuery阿賈克斯):

$(document).ready(function() { 
    autoRefresh(); 
}); 
function autoRefresh() { 
    $.ajax({ 
     method: 'POST', 
     url: "php/placement-load.php", 
     success: function(data) { 
      $('#placement-table').html(data); 
     } 
    }); 
} 

表體也將加載得很好,但如果我點擊編輯(在錨標記)該模式將不起作用。

爲什麼?

+1

我的猜測是,使用AJAX方法'edit'事件偵聽器都已經到位,Ajax是在新內容中提取出來太晚了他們與功能分配。 – NewToJS

+1

[如何在bootstrap中打開模式,如果通過ajax加載]可能的重複?(http://stackoverflow.com/questions/28495266/how-to-open-a-modal-in-bootstrap-if-this -is-loaded-via-ajax) – vijayP

+0

其中是編輯按鈕? –

回答

0

當你通過ajax加載數據,這就是爲什麼早先jquery已經綁定到DOM中的HTML綁定不在新的HTML元素添加到DOM。

在這種情況下,我們需要再次執行已經在頁面上執行的jQuery,以將它們與新添加的html綁定。

我採取的方法是創建一個名爲bind的函數,並添加所有不再工作的jQuery事件,並在文檔的ready事件中調用它,並在完成ajax調用時調用該函數。以下片段供參考:

function autoRefresh() { 
    $.ajax({ 
     method: 'POST', 
     url: "php/placement-load.php", 
     success: function(data) { 
      $('#placement-table').html(data); 
      bind(); //Calling bind function on ajax call success 
     } 
    }); 
} 

//Define bind function 
function bind(){ 
    //Add code to open the modal here 
    //You can add all the jquery code which is not executing after loading the data from ajax 
} 

//calling bind() along with your autoRefresh function 
$(document).ready(function() { 
    autoRefresh(); 
    bind(); 
}); 
相關問題