2013-06-25 97 views
0

我在html中创建一个表,然后将其填充到下表(drawTable在我的document.ready函数中调用)。对于每一行,末尾有一个按钮,用于添加具有相同ID的另一行,并直接插入下方。表(#fieldTable)td元素的clicked处理程序对最初插入的所有按钮都正常工作。当他们点击“+”按钮时,它会在最后添加带有“ - ”按钮的行。现在这个在屏幕上显示得很好,但是当点击时,表单点击处理程序不会被触发,但是文档却可以。在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'元素 –

相关问题