2012-10-13 3 views
2

데이터베이스에서 파싱 된 JSON 배열이 있습니다.json 생성 테이블에 onclick 추가

$.getJSON(… , 

이 데이터는 표 1에 이름 배치 $.each으로 반복 처리된다.

function(geojson) { 
    $.each(geojson.features, function(i, feature) { 
     var id = feature.properties.id; 
     var name = feature.properties.name; 
     var otherDetails = feature.properties.otherDetails; 

     // Populate table1 with clickable links 
     $("#table1 table").append('<tr><td><a href="#" onclick="['+id+']; return false;">'+name+'</a></td></tr>') 
      //populate table2 with name 
      .click(function(){ 
       $("#table2 table").append('<tr><td><a">'+name+' '+otherDetails+'</a></td></tr>') 
     }) 
    }); 
}); 

이것은 모두 훌륭합니다. 테이블에있는 'name'의 각 기능을 클릭 할 수 있습니다. 하나의 레코드에 대해서만 'name'및 'otherDetails'로 다른 테이블 (table2)을 채우고 싶습니다. 위의 코드는 거의 저를 데려 오지만, 클릭 한 기능의 이름으로 table2를 채우려는 의도로 table2를 테이블 1의 거의 모든 복사본으로 채 웁니다. 아직 $.each 안에 있기 때문에 생각합니다. 중첩 된 추가에서 각 반복을 중지 할 수 있습니까? 미리 감사드립니다.

답변

0

table1의 행에 클릭 핸들러를 추가하십시오. 클릭하면 테이블 2의 새 행에 넣을 이름을 뽑아냅니다.

$('#table1 table').on('click', 'tr', function() 
{ 
    var name = $(this).find('a').text(); 
    $('#table2 table').append('<tr><td><a">' + name + '</a></td></tr>'); 
}); 

변경된 데이터 유지 방법은 data attributes입니다. 이렇게하면 otherinfo 데이터도 사용할 수 있습니다.

1

click 이벤트 핸들러가 table 레벨에 반복적으로 적용됩니다. 다음과 같이 행에 적용 해보세요.

// Populate table1 with clickable links 
var newRow = $('<tr><td><a href="#" onclick="['+id+']; return false;">'+name+'</a></td></tr>'); 
$("#table1 table").append(newRow); 
$(newRow).click(function(){ 
    $("#table2 table").append('<tr><td><a">'+name+' '+otherDetails+'</a></td></tr>') 
}); 
+0

매력처럼 작동했습니다. – Bwyss

관련 문제