首页 > 解决方案 > 找到正确的选择器:在 jquery 中将 div 添加到父级

问题描述

我有这个html结构:

<div class="dropdownedit">
<div class="dropbtn">textxyz</div>
<div class="dropdown-content" style="display: none;">
<div href="#" class="ocond" id="text1">text1</div>
<div href="#" class="ocond" id="text2">text2</div>
<div href="#" class="ocond" id="text3">text3</div>
<div href="#" class="ocond" id="text4">text4</div>
</div></div>

现在我想添加一个新的 div 行<div href="#" class="ocond" id="text0">text0</div>

到下拉内容类。这应该在$("#table_cards").on( 'click', 'div.ocond', function (e) {...“ocond”类(下拉内容类内部)的点击事件 ( ) 内完成。

我已经尝试了这两个选项:

$(this).closest('.dropdown-content').prepend('<div ... >text0</div>');

$(this).parent('.dropdown-content').prepend('<div ... >text0</div>');

但两者都不起作用。单击“ocond”类时,我找不到正确的选择器来实现这一点。感谢您提前提供任何帮助!

标签: javascriptjqueryselector

解决方案


.parent()不接受选择器,因为它只是上升了一级。

.parents()这样做是因为它通过父母、祖父母等不断上升,并且只会影响与选择器匹配的那些元素。

.closest()接受一个选择器,.parents()但在找到第一个满足选择器的父级后会停止。

您可以使用.parent().prepend(), 或.closest(".dropdown-content").prepend()

$(".dropbtn").click( function() { 
  $(this).nextAll(".dropdown-content").first().show();
});

$(".dropdownedit").mouseleave( function() { 
  $(this).find(".dropdown-content").hide();
});

$(".ocond").click( function() { 
  $(this).closest('.dropdown-content').prepend("<div href='#' class='ocond' id='text0'>text0</div>");
  $(this).closest('.dropdown-content').hide(); 
});
.dropdown-content {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="dropdownedit">
  <div class="dropbtn">textxyz</div>
  <div class="dropdown-content">
    <div href="#" class="ocond" id="text1">text1</div>
    <div href="#" class="ocond" id="text2">text2</div>
    <div href="#" class="ocond" id="text3">text3</div>
    <div href="#" class="ocond" id="text4">text4</div>
  </div>
</div>


推荐阅读