簡體   English   中英

如果子div包含某個數據屬性,則刪除父div

[英]Remove parent div if child div contains a certain data attribute

由於我是動態進行的,因此我必須檢查main div是否與某個user-id匹配。 如果是這樣,請深入其中並做額外的工作。 讓我告訴你我在說什么。

<div class="col-md-6 user-card-holder" data-user="2">
  <div class="col-xs-2 single-card">
    <div class="house" data-house="hearts" data-value="q">Q-hearts</div>
  </div>
</div>

有許多div's具有類名user-card-holder 我必須使用data-user屬性檢查特定的對象。 現在我正在檢查的是:

如果div包含具有hearts值的data-house以及具有q值的data-value ,則將該div及其父級移除。 這里的parent是指具有single-card類而不是user-card-holderdiv

我嘗試使用filter() 也許我在這里做錯了。

 $('.user-card-holder[data-user='+ card.user +'] div div').filter(function(){

     var div = $(this).data('house') == card.house && $(this).data('value') == card.number;
      return div.parent()


     }).remove();

我已經看到了答案,該答案顯示了根據data屬性刪除元素,但不是父元素。

我建議:

// this finds all <div> elements with a
// 'data-house' attribute equal to 'hearts' and a
// 'data-value' attribute equal to 'q':
$('div[data-house=hearts][data-value=q]')
  // traverses to the parent of the matching element(s):
  .parent()
  // removes the parent element(s) from the DOM:
  .remove();

另外,如果您正在動態搜索祖先以找到要刪除的適當元素,那么在重新閱讀您的問題時似乎就是這種情況:

// finds <div> element(s) with the class of 'user-card-holder'
// and the 'data-user' attribute equal to the value of the 'card.user'
// variable, and finds the descendant <div> element(s) matching
// the selector used above:
$('div.user-card-holder[data-user=' + card.user + '] div[data-house=hearts][data-value=q]')
  // traverses to the parent of the descendant element:
  .parent()
  // removes the parent element of that descendant:
  .remove();

參考文獻:

試試這個功能:

removeCardFromUser(2);

function removeCardFromUser(id) {
    $('.user-card-holder').filter(function(){
        var user = $(this).data('user');
        if (user === id) {
            $(this).find('div').filter(function(){
                var house = $(this).data('house');
                var value = $(this).data('value');
                if (house === 'hearts' && value === 'q') {
                    $(this).parent().remove();
                }
            });
        }
    });
}

它使用類'user-card-holder'和data-user = {given id}查找div,然后使用data-house ='hearts'和data-value ='q'查找其后代並刪除其父級。

大衛的答案就足夠了! :)

暫無
暫無

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

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