我有这个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>
到下拉内容类。这应该在“ ocond”类(在dropdown-content类的内部)的单击事件($("#table_cards").on( 'click', 'div.ocond', function (e) {...
)内完成。
我尝试了这两个选项:
$(this).closest('.dropdown-content').prepend('<div ... >text0</div>');
和
$(this).parent('.dropdown-content').prepend('<div ... >text0</div>');
但是两者都不起作用。单击“ ocond”类时,找不到正确的选择器。 谢谢您提前提供帮助!
答案 0 :(得分:2)
.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>