2013-06-25 4 views
0

html로 테이블을 만든 다음 아래 테이블에 채 웁니다 (drawTable이 내 document.ready 함수에서 호출 됨). 각 행에는 마지막에 바로 아래에 삽입 된 동일한 ID를 가진 다른 행을 추가하는 버튼이 있습니다. 테이블 (#fieldTable) 요소의 클릭 핸들러는 처음 삽입 된 모든 버튼에 대해 잘 작동합니다. 그들이 "+"버튼을 클릭하면 끝에 "-"버튼이있는 행이 추가됩니다. 이제는 화면에 잘 보이지만 클릭하면 테이블 핸들러가 눌려서 작동하지 않습니다.하지만 문서는 실행됩니다.jquery에서 동적으로 생성 된 버튼에 대한 클릭 핸들러

제거 ("-") 버튼을 클릭하고 테이블에서 해당 행을 삭제할 수 있기를 원합니다.

function drawTable() { 
    //fill a table I created in html, (not important for this question) 
      //it now looks like this 
    | ID | NAME | VALUE | ACTION | 
    | 1 | Test | <input> | + | 
      | 2 | Test2 | <input> | + | 

    //where the action column is a button (+ indicates create a new row) 
    //so when they click the grid this gets called 
    $('#fieldTable td').click(function() { 
    var row = $(this).parent().parent().children().index($(this).parent()); 
    var col = $(this).parent().children().index($(this)); 
    if(col != 3) 
    { 
     return; 
    } 
    var text = $(this).parents('tr').find('td:last').text(); 
    var etiId = $(this).parents('tr').find('td:first').text(); 
    console.log(text); 
    if(text == "+") 
    { 
     var $tr = $(this).closest('tr'); 
     var $clone = $tr.clone(); 
     $clone.find(':text').val(''); 
     $clone.find('td:nth-child(2)').text(''); 
     $clone.find('td:nth-child(4)').find('button').text('-'); 
     $tr.after($clone); 
    } 
    //so now the grid would look like this 
    | ID | NAME | VALUE | ACTION | 
    | 1 | Test | <input> | + | 
    | 1 |  | <input> | - | 
    | 2 | Test2 | <input> | + | 

    //the issue is, if I click the "-" button, this handler does not get called 
    // the document.on('click'...) does, but I am not sure how to determine the 
    // row/column of the button click and then remove that row 
    else if(text == "-") 
    { 
     console.log("remove"); 
     $(this).parent().parent().remove(); 
    } 
    }); 

    $(document).on('click', '.btnAddRemove', function() { 
     console.log("document cliked"); 
    }); 
} 

답변

2

이벤트 위임을 사용하십시오.

$("#fieldTable").on("click", "td", function() { 

당신이 td가 동적으로 생성되기 때문에 제대로 작동하려면이를 얻기 위해 변경해야하는 것은해야하지만, #fieldTable는 항상있을 것입니다.

+0

그럼 여전히 같은 $ (this) 객체와 모든 것을 참조 할 것입니까? – Andrew

+0

@Andrew 네,'td' 요소를 참조 할 것입니다. –

관련 문제