2013-03-28 96 views
1

如何删除我的表格行onClick事件?mootools使用HtmlTable动态添加/删除表格行

var count = 0, 
     optionsTable  = new HtmlTable({ 
       properties: {id: 'optionstable', border: 0, cellspacing: 0, width: "100%"}, 
       headers: ['Name', 'Value', 'Price', 'Action']        
      }).inject(container); 

     optionsTable.push(['<input type="text" name="option[0][name]" class="w70">', 
        '<input type="text" name="option[0][value]" class="w50">', 
        '<input type="text" name="option[0][price]" class="w50">', 
        '<a href="javascript:void(0);" class="add_option">Add</a>' 
       ]); 

     $$('.add_option').addEvent('click', function(){ 
      count ++; 
      optionsTable.push(['<input type="text" name="option['+count+'][name]" class="w70">', 
       '<input type="text" name="option['+count+'][value]" class="w50">', 
       '<input type="text" name="option['+count+'][price]" class="w50">', 
       '<a href="javascript:void(0);" class="product_remove_option">Remove</a>' 
      ]); 
     }); 

     $$('.product_remove_option').addEvent('click', function(){ 
      /*What should be here to remove selected table row?*/       
     }); 

回答

1

首先,您应该确保始终将事件添加到新创建的元素(或使用事件委派)。

回答您的问题:HtmlTable.push方法返回一个包含添加的表格行和表格单元格的对象。您只需在表格行上拨打destroy即可将其删除。

下面的代码应该是什么样子:

var count = 0, 
    optionsTable  = new HtmlTable({ 
      properties: {id: 'optionstable', border: 0, cellspacing: 0, width: "100%"}, 
      headers: ['Name', 'Value', 'Price', 'Action']        
     }).inject(container); 

var firstRow = optionsTable.push(['<input type="text" name="option[0][name]" class="w70">', 
      '<input type="text" name="option[0][value]" class="w50">', 
      '<input type="text" name="option[0][price]" class="w50">', 
      '<a href="javascript:void(0);" class="add_option">Add</a>' 
     ]); 

firstRow.tr.getElement('.add_option').addEvent('click', function(){ 
    count ++; 
    var newRow = optionsTable.push(['<input type="text" name="option['+count+'][name]" class="w70">', 
     '<input type="text" name="option['+count+'][value]" class="w50">', 
     '<input type="text" name="option['+count+'][price]" class="w50">', 
     '<a href="javascript:void(0);" class="product_remove_option">Remove</a>' 
    ]); 
    newRow.tr.getElement('.product_remove_option').addEvent('click', function(){ 
     newRow.tr.destroy(); 
    });     
}); 
1

这应该做你想要什么:

$('optionstable').getElements('tr').addEvent('click',function(){ 
    this.destroy(); 
});