查找正确的选择器:将 div 添加到 jquery 中的父级

Finding the correct selector for: add div to parent in jquery

我有这个 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>

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

我试过这两个选项:

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

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

但两者都没有 work.I 在单击 "ocond" class 时找不到正确的选择器来实现此目的。 提前感谢您的帮助!

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

.parents() 之所以如此,是因为它不断上升通过 parents、grandparents 等,并且只会影响那些与选择器匹配的元素。

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

您可以使用.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>