2014-04-11 4 views
0

Ajax 응답을 통해 jquery에서 테이블을 채우고 있습니다. 자세한 정보를 입력하려면 표의 행을 클릭해야합니다. 나는 다음과 같은 코드의 row_id를 추출하는 행을 클릭하면 :테이블 행이 페이지 소스에 나타나지 않습니다.

(function(){ 
    $('#bags_table tr').click(function() { 
      alert(1) 
      alert($(this).attr('id')); //trying to alert id of the clicked row   

    }); 
}); 

를 행을 클릭하면, 경고가 발생하지 않습니다. 페이지 소스를 보면 빈 테이블이 표시됩니다.

다음과 같은 표가 생성됩니다.

function bags_table_func(result){ 

    var rows = "<tr><th>Seal No.</th><th>Status</th><th>Destination</th><th>Total Packets</th><th>Max. Weight</th>" + 
       "<th>Min. Weight</th><th>Avg. Weight</th><th>Total Weight</th></tr>" 

    for (var obj in result){ 
     if (obj == 'last_bagged_on'){ 
       continue 
     } 
     else if (result[obj]['status'] == undefined){ 
      rows += "<tr><td>No Content</td></tr>" 
      break 
     } 
     rows += "<tr id = '"+obj+"'><td>" + obj+"</td><td>" + result[obj]["status"] + "</td><td>" + 
        result[obj]["destination"] + "</td><td>" + result[obj]["total_packets"] + "</td><td>" + 
        result[obj]["max_weight"] + "</td><td>" + result[obj]["min_weight"] + "</td><td>" + 
        result[obj]["avg_weight"] + "</td><td>" + result[obj]["total_weight"] + "</td><td><a href = '#'>Details</td></tr>" 
    } 
    $("#bags_table").html(rows); 
} 

방법 테이블 생성 된 Ajax 응답이 를 클릭 내가 할 수 ?

답변

0

당신이 코드를 통해 테이블을 생성하고 동적 당신이 event delegation method

$(document).on('click','#bags_table tr',function() { 
    alert(1) 
    alert($(this).attr('id')); //trying to alert id of the clicked row   
}); 
0

.on()

$(document.body).on('click','#bags_table tr',function() { 
    alert(1) 
    alert($(this).attr('id')); //trying to alert id of the clicked row   
}); 
테이블 행이 런타임에 추가됩니다

, 런타임 추가 요소 event delegation을 시도 사용해야로 보기 원본에 표시 할 수 없으며 네이티브 이벤트를 해당 요소에 바인딩 할 수 없습니다. 동일한 이벤트 위임이 필요합니다.

여기에 document/document.body 대신 가장 가까운 상위 요소를 가질 수 있습니다.

관련 문제