由于我是动态进行的,因此必须检查主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包含值为data-househearts以及值为data-valueq,则将该div及其父级删除。这里的parent表示具有类divsingle-card而不是user-card-holder

我尝试使用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();


参考文献:


CSS:


Attribute-selectors

jQuery的:


parent()
remove()

关于javascript - 如果子div包含某个数据属性,则删除父div,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40267270/

10-13 08:14
查看更多