2016-06-19 92 views
1

所以我有一张桌子。通过点击一个按钮,信息将被添加到那里,所以每个项目也有X按钮,它们从列表中删除它们。我一直在试图做到这一点,如果你点击那个X按钮,那么它会输出到控制你删除的项目名称。我怎么能这样做?Javascript - 从表中删除项目名称?

这里的功能

function sitaSeen(img, name, condition, price) { 
    $('tbody').append("<tr id='itemCart'><td><img src=" + img + "></td><td>" + name + "</td><td>" + condition + "</td><td>$" + price + "</td><td><span>X</span></td></tr>"); 

被称为,当项目已被添加。

这里的X按钮代码

$(document).ready(function() { 
    $('.sweet-container').on('click', 'tr span', function(){ 
     var removedname = $(this).closest('tr').ignore('span').text(); 
     console.log(removedname); 
     $(this).closest('tr').remove(); 
    }); 
}); 

还有一种我尝试,但OFC它不会工作。

回答

0

在jQuery中没有ignore()方法,所以它会在控制台中抛出错误。因此,要克隆tr并从克隆对象中删除span,然后获取文本或获取所有不包含span的td并获取文本。

$(document).ready(function() { 
    $('.sweet-container').on('click', 'tr span', function(){ 
     var removedname = $(this).closest('tr').clone().remove('span').text(); 
     // or 
     // var removedname = $(this).closest('tr').find('td:not(:has(span))').text(); 
     console.log(removedname); 
     $(this).closest('tr').remove(); 
    }); 
}); 

UPDATE:既然你只是想第二列,你可以简单地使用:nth-child:eq()选择(或eq())。

$(document).ready(function() { 
    $('.sweet-container').on('click', 'tr span', function(){ 
     var removedname = $(this).closest('tr').find('td:nth-child(2)').text(); 
     // or 
     // $(this).closest('tr').find('td:eq(1)').text(); 
     // or 
     // $(this).closest('tr').children().eq(1).text(); 
     console.log(removedname); 
     $(this).closest('tr').remove(); 
    }); 
}); 
+0

谢谢先生!它的工作原理,只有一个问题,它获得了所有的价值。像表中有3个值,名称条件和价格,然后输出它们全部。 –

+0

@AleksKpur:确定你想要实际获得哪一列? –

+0

名称列如此第二个 –

0

我想这可能是更好的使用:

``` //更好的方式去tr元素

VAR trElem = $(本).parentNode.parentNode; ```

parentNode属性是访问元素父项的更好方法。

0

项目名称是第二个TD所以你可以使用:

var removedname = $(this).closest('tr').find('td:eq(1)').text(); 

因为ID必须是唯一我添加了一个新的参数给你的函数。

function sitaSeen(seq, img, name, condition, price) { 
 
    $('tbody').append("<tr id='itemCart" + seq + "'>" + 
 
        "<td><img src=" + img + "></td>" + 
 
        "<td>" + name + seq + "</td>" + 
 
        "<td>" + condition + "</td>" + 
 
        "<td>$" + price + "</td>" + 
 
        "<td><span>X</span></td>" + 
 
        "</tr>"); 
 
} 
 
$(function() { 
 
    $('#addRow').on('click', function(e) { 
 
    var seq = +$(this).attr('data-seq'); 
 
    $(this).attr('data-seq', seq + 1); 
 
    sitaSeen(seq, 'img', 'name', 'condition', 'price'); 
 
    }); 
 

 
    $('.sweet-container').on('click', 'tr span', function(){ 
 
    var removedname = $(this).closest('tr').find('td:eq(1)').text(); 
 
    console.log(removedname); 
 
    $(this).closest('tr').remove(); 
 
    }); 
 
});
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script> 
 

 
<div class="sweet-container"> 
 
    <button id="addRow" data-seq="1">Add Row</button> 
 
    <table> 
 
     <tbody> 
 

 
     </tbody> 
 
    </table> 
 
</div>