문제

jQuery로 테이블 행을 제거하는 가장 좋은 방법은 무엇입니까?

도움이 되었습니까?

해결책

네가 옳아:

$('#myTableRow').remove();

당신의 행에 당신이있는 경우에도 잘 작동합니다 id, 와 같은:

<tr id="myTableRow"><td>blah</td></tr>

당신이 없다면 id, 당신은 jQuery를 사용할 수 있습니다 수많은 선택기.

다른 팁

$('#myTable tr').click(function(){
    $(this).remove();
    return false;
});

테이블에 데이터 셀 내부에 버튼/링크가 있다고 가정하면 이와 같은 일이 트릭을 수행 할 것입니다 ...

$(".delete").live('click', function(event) {
    $(this).parent().parent().remove();
});

이렇게하면 클릭 한 버튼/링크의 부모의 부모가 제거됩니다. Parent ()는 일반적인 dom 객체가 아닌 jQuery 객체이기 때문에 Parent ()를 사용해야하며, 버튼은 데이터 셀 내부에 살면서 행 내부에 사는 것입니다. 제거하고 싶은 것. $ (this)는 클릭 한 버튼이므로 이와 같은 것이 있으면 버튼 만 제거합니다.

$(this).remove();

이것은 데이터 셀을 제거하지만 :

    $(this).parent().remove();

행의 어느 곳을 클릭하여 간단히 클릭하려면 이와 같이 제거 할 수 있습니다. 이를 쉽게 수정하여 사용자에게 프롬프트를하거나 두 번 클릭 할 수 있습니다.

$(".delete").live('click', function(event) {
    $(this).parent().remove();
});

그것이 도움이되기를 바랍니다 ... 나는 이것에 대해 조금 어려움을 겪었습니다.

당신이 사용할 수있는:

$($(this).closest("tr"))

요소의 부모 테이블 행을 찾는 것.

부모님 (). 부모 ()보다 더 우아합니다.

-EDIT- 누군가 문제가 행을 제거하는 것에 관한 것이라고 지적했습니다 ...

$($(this).closest("tr")).remove()

아래에 지적 된 바와 같이, 당신은 간단히 할 수 있습니다 :

$(this).closest('tr').remove();

유사한 코드 스 니펫은 여러 요소에서 이벤트를 발사하는 것과 같은 많은 작업에 사용할 수 있습니다.

쉽게 .. 이걸 시도하십시오

$("table td img.delete").click(function () {
    $(this).parent().parent().parent().fadeTo(400, 0, function () { 
        $(this).remove();
    });
    return false;
});

다음과 같은 수용 가능 :

$('#myTableRow').remove();
function removeRow(row) {
    $(row).remove();
}

<tr onmousedown="removeRow(this)"><td>Foo</td></tr>

어쩌면 이런 것이 효과가 있을까요? 나는 "this"로 무언가를 시도하지 않았으므로 그것이 작동하는지 아닌지 모르겠습니다.

테이블 행을 제거하기 만하면됩니다.<tr>) 테이블에서 태그. 예를 들어 여기에 테이블에서 마지막 행을 제거하는 코드가 있습니다.

$('#myTable tr:last').remove();

*위의 코드는 가져 왔습니다 이 jQuery howto post.

크기에 대해 이것을 시도하십시오

$(this).parents('tr').first().remove();

전체 목록 :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
        $('.deleteRowButton').click(DeleteRow);
      });

    function DeleteRow()
    {
      $(this).parents('tr').first().remove();
    }
  </script>
</head>
<body>
  <table>
    <tr><td>foo</td>
     <td><a class="deleteRowButton">delete row</a></td></tr>
    <tr><td>bar bar</td>
     <td><a class="deleteRowButton">delete row</a></td></tr>
    <tr><td>bazmati</td>
     <td><a class="deleteRowButton">delete row</a></td></tr>
  </table>
</body>
</html>

실제로보십시오

다른 하나 empty() :

$(this).closest('tr').empty();

삭제하려는 행이 변경되면 이것을 사용할 수 있습니다. 이 함수를 삭제하려는 행을 전달하십시오.

function removeMyRow(docRowCount){
   $('table tr').eq(docRowCount).remove();
}
$('tr').click(function()
 {
  $(this).remove();
 });

위의 코드를 사용해 볼 것이라고 생각하지만 언젠가는 왜 작동하는지 모르고 전체 테이블이 제거됩니다. 또한 행을 클릭하여 행을 제거하려고합니다. 그러나 정확한 답변을 찾을 수 없었습니다.

이렇게 HTML이 있다면

<tr>
 <td><span class="spanUser" userid="123"></span></td>
 <td><span class="spanUser" userid="123"></span></td>
</tr>

어디 userid="123" 테이블을 만들 때 동적으로 채울 수있는 사용자 정의 속성입니다.

당신은 같은 것을 사용할 수 있습니다

  $(".spanUser").live("click", function () {

        var span = $(this);   
        var userid = $(this).attr('userid');

        var currentURL = window.location.protocol + '//' + window.location.host;
        var url = currentURL + "/Account/DeleteUser/" + userid;

        $.post(url, function (data) {
          if (data) {
                   var tdTAG = span.parent(); // GET PARENT OF SPAN TAG
                   var trTAG = tdTAG.parent(); // GET PARENT OF TD TAG
                   trTAG.remove(); // DELETE TR TAG == DELETE AN ENTIRE TABLE ROW 
             } else {
                alert('Sorry, there is some error.');
            }
        }); 

     });

따라서이 경우에 클래스 나 ID를 모릅니다. TR 태그이지만 어쨌든 삭제할 수 있습니다.

나는 이것이 오래된 게시물이라는 것에 감사하지만, 나는 똑같이하려고했고, 받아 들여진 대답이 나에게 효과가 없다는 것을 알았습니다. jQuery가 쓰여진 이후로 이동했다고 가정합니다.

어쨌든, 나는 다음이 나를 위해 일했다는 것을 알았습니다.

$('#resultstbl tr[id=nameoftr]').remove();

이것이 누군가를 돕는 지 확실하지 않습니다. 위의 예제는 더 큰 기능의 일부 였으므로 이벤트 리스너에 래핑하지 않았습니다.

부트 스트랩 테이블을 사용하는 경우

이 코드 스 니펫을 bootstrap_table.js에 추가하십시오

BootstrapTable.prototype.removeRow = function (params) {
    if (!params.hasOwnProperty('index')) {
        return;
    }

    var len = this.options.data.length;

    if ((params.index > len) || (params.index < 0)){
        return;
    }

    this.options.data.splice(params.index, 1);

    if (len === this.options.data.length) {
        return;
    }

    this.initSearch();
    this.initPagination();
    this.initBody(true);
};

그럼 당신의 var allowedMethods = [

추가하다 'removeRow'

마지막으로 사용할 수 있습니다 $("#your-table").bootstrapTable('removeRow',{index:1});

이 게시물에 대한 크레딧

ID는 이제 좋은 선택기가 아닙니다. 행의 일부 속성을 정의 할 수 있습니다. 그리고 당신은 그것들을 선택기로 사용할 수 있습니다.

<tr category="petshop" type="fish"><td>little fish</td></tr>
<tr category="petshop" type="dog"><td>little dog</td></tr>
<tr category="toys" type="lego"><td>lego starwars</td></tr>

그리고 func를 사용하여 다음과 같은 행을 선택할 수 있습니다 (ES6).

const rowRemover = (category,type)=>{
   $(`tr[category=${category}][type=${type}]`).remove();
}

rowRemover('petshop','fish');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top