簡體   English   中英

如何使用jQuery檢查另一個元素/標簽內是否沒有元素/標簽

[英]How to check if there are no elements/tags inside another element/tag with jQuery

我在整個Stack Overflow網站上都進行了搜索,但可以找到答案

<tbody>沒有<tr>時,下面的代碼不會顯示任何警報,這是為什么?

我確定以下方法可以工作,但是什么也沒發生:

<script>
  $('td > a').click(function(e){
  var this_elem = $(this);

  if( this_elem.hasClass("remove") ){
    this_elem.parent().parent().remove();
  }

  return false;

 });

 if( $("tbody > tr").length === 0 ){

  alert("No more rows of products...");

 }
</script>

HTML:

<table>
 <tbody>
  <tr>
   <td class="first-td">
    <img src="assets/product-image.jpg" alt="product image" />

    <div class="prod-desc-col">
     <h3>Samsung LE40C580J1 LCD HD 1080p Digital Television, 40 Inch with Built-in Freeview HD, Samsung LE40C580J1 LCD HD 1080p Digital Television, 40 Inch with Built-in Freeview HD</h3>
     <p>Product Code: 1254782</p>
     <p>In stock</p>
    </div>
   </td>
   <td>
    <input type="text" value="1" size="4" />
    <a href="#" title="Update" class="update">Update</a>
    <a href="#" title="Remove" class="remove">Remove</a>
   </td>
  </tr>
 </tbody>
</table>

因為你不計算下一行,您要統計所有行的tbody中的所有 table在頁面秒。

考慮到添加到該問題的其他詳細信息,我向您提供以下內容:

$('a.remove').click(

function() {
    $(this).closest('tr').remove(); // a slightly more concise form of your own code
    return false;
});

$('table tbody').bind('DOMNodeRemoved', function() {
    var c = $('table tbody tr').length;
    if (c === 1) { // testing against '1' because the count is performed before
                   // the row is actually removed from the DOM.
        alert("The final row is about to go.");
    }
});

JS小提琴演示

頁面中只有一張桌子嗎? 否則,您將計算頁面中所有表中的所有行。

要計算行數,您可以在這里查看我的測試: http : //jsfiddle.net/2DDZz/

編輯:

當您發布代碼時,我看到您僅在頁面加載時檢查行數。 每次刪除行時,都應檢查它:

$('td > a').click(function(e){
  var this_elem = $(this);
  if( this_elem.hasClass("remove") ){
    this_elem.parent().parent().remove();

    if( $("tbody > tr").length === 0 ){
      alert("No more rows of products...");
    }

  }
  return false;
});

您沒有為我們提供太多信息,但是我的第一個猜測是您的JQuery選擇器在頁面上的ANY表中查找行。 如果頁面中還有其他表,則這些行也可能被計數。 您需要做的是使您的JQuery選擇器更加具體。 例如:

if( $(" #myTableName > tbody > tr").length === 0 ){
    alert("No more rows of products...");
}

注意,我已經向選擇器添加了一個ID。 這告訴JQuery只在表中查找ID為“ myTableName ”的行。

也許您應該考慮使用nextAll

http://api.jquery.com/nextAll/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM