2016-06-19 91 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>