簡體   English   中英

將onclick方法添加到動態創建的表行中

[英]Add onclick method to dynamically created table rows

我有一個表,該表中填充了使用ajax從數據庫中獲取的用戶列表,並且在每個用戶名旁邊都有一個展開/最小化圖標,希望該用戶能夠單擊以顯示有關該用戶的更多信息。

示例:HTML表

<table class = "table" name="pData" id="<?php echo $patientId ?>">
</table>

用來填充表的Javascript :(在成功的Ajax調用中,對每個用戶進行迭代,並為每個用戶添加以下內容)

tableData = "<tr>
             <td>
            <img src = 'expandIcon.png' onclick='showUserInfo("+UserId+", 'Max')'/>       
            </td>";
tableData += "<td colspan = '2'>"+userName+"</td>";
tableData += "<td>&nbsp;</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td>&nbsp</td>
               </tr>";

$('.table').append(tableData);

我的表是以我想要的方式創建的,但是onclick事件從未發生,並且showUserInfo從未被調用。 我該如何解決呢?

在元素中添加一個類,如下所示:

tableData = "<tr>
              <td>
              <img class='anyclass' id="+UserId+" src = 'expandIcon.png'/>
             </td>";
tableData += "<td colspan = '2'>"+userName+"</td>";
tableData += "<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp</td></tr>";
$('.table').append(tableData);

然后編寫如下的jquery事件:

$(document).ready(function(){


$(img.anyclass).live('click',function(){

showUserInfo(this.id, 'Max');


});

});

正確關閉img標簽

"<tr><td><img src = 'expandIcon.png' onclick='showUserInfo("+UserId+", 'Max')'/></td>";

我檢查了您的代碼,發現級聯有問題:

tableData = "<tr><td><img src = 'expandIcon.png' onclick='showUserInfo(\'"+UserId+"\', \'Max\')'></td>";
tableData += "<td colspan = '2'>"+userName+"</td>";
tableData += "<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp</td> </tr>";
$('.table').append(tableData);

當表元素中有大量行時,使用“事件委托”會更有效率。

首先創建您的行:

var newRow = '<tr><td><img src='expandIcon.png' /></td></tr>';

現在將其添加到表的末尾:

$('#yourtable tr:last').after(newRow);

將事件處理程序動態綁定到行(或圖像):

$('#yourtable').on('click', 'tr', function (event) {
    // do your stuff here
});

假設您的表中有100行,如果遵循常規方法,則處理程序將附加到100個元素。 使用事件委托時,事件處理程序僅附加一個元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM