javascript - 找到正确的选择器:在 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”类时,我找不到正确的选择器来实现这一点。感谢您提前提供任何帮助!
解决方案
.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>
推荐阅读
- javascript - 如何从 Vuetify 列表中的 Vuex 商店获取状态,VueJs
- c# - 我的 TFS 代理没有自动工作
- regex - 我如何编写一个只允许数字和逗号以及字符串开头和结尾的数字的正则表达式?
- ajax - 实现自动完成:为什么在输入任何字符之前调用 AJAX?
- salesforce - Salesforce - 查询以从联结对象和客户中获取数据
- java - 如何使用 IP 地址共享我的数据库?
- javascript - 在输入更改时,获取 div 中的所有输入值并更新标签
- android - 在一台设备上“未安装应用程序”
- azure - 每个数据库、每个帐户或每个 Cosmos Db 订阅的集合是否有任何限制(多少)?
- airflow - 如何在 Airflow 中动态塑造 DAG