使用 jQuery 检索子按钮的特定父级
Retrieve a specific parent of child button using jQuery
我有这个html结构(非常通用),div的id是通过一个创建顺序对象的函数动态添加的:
<div id="mydiv1">
<div> Stuff</div>
<div>
<button id="remove"></button>
</div>
</div>
"删除"按钮应该删除他所在的div,所以我必须检索div 的 id 才能做到这一点。我不知道怎么做。如何使用jQuery制作?谢谢
<form>
<div id="mydiv1">
<div> Stuff</div>
<div>
<button id="remove"></button>
</div>
</div>
<div id="mydiv2">
<div> Stuff</div>
<div>
<button id="remove"></button>
</div>
</div>
</form>
我试过了:
("#remove").click(function(event) {
var id = event.target.id;
}
但结果是:"删除"而不是"mydiv1"或"mydiv2"
您应该使用 class
而不是 id
作为按钮(id
应该是唯一的):
$('.remove').click(function() {
$(this).closest('div[id^="mydiv"]').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<div id="mydiv1">
<div>Stuff 1</div>
<div>
<button class="remove">REMOVE</button>
</div>
</div>
<div id="mydiv2">
<div>Stuff 2</div>
<div>
<button class="remove">REMOVE</button>
</div>
</div>
</form>
编辑:更新为OP发布的新代码
对于 mydiv2 更改按钮,如下所示:
$(".remove").click(function() {
var id = $(this).data('id');
$("#mydiv"+id).remove();
}
<button class="remove" data-id="2"></button>
使用 $(this).parent('div')
获取类型为 <div>
的第一个父节点
$("#remove").click(function(event) {
var parent = $(this).parent('div');
parent.remove();
}
编辑
因此,在您的div中添加一个类,例如.divRow
<form>
<div id="mydiv1" class="divRow">
<div> Stuff</div>
<div>
<button id="remove"></button>
</div>
</div>
<div id="mydiv2" class="divRow">
<div> Stuff</div>
<div>
<button id="remove"></button>
</div>
</div>
</form>
在这种情况下,您的JavaScript将
$("#remove").click(function(event) {
var parent = $(this).parent('.divRow'),
id = parent.attr("id");
alert(id);
parent.remove();
}
尝试
$('.remove').click(function() {
var id = $(this).parent().parent().attr('id');
//This will give you the id
});
对于问题的下一部分,请尝试以下操作:
$(document).on('click','.remove',function() {
var id = $(this).parent().parent().attr('id');
//This will give you the id
});
相关文章:
- 验证动态单选按钮jQuery
- 单击按钮-jQuery/JavaScript时显示表格
- 加载页面时未触发按钮?(JQuery)
- 菜单打开和关闭菜单按钮 - Jquery
- FlatUI - 单选按钮 jQuery 兼容性
- 动作脚本3中的链接按钮 + jQuery 集成中的淡出
- 使用用户名时禁用按钮 jQuery.
- 需要默认的CSS按钮(JQuery)
- 如何将单选按钮的选定值复制到另一个单选按钮 - jquery
- 单击另一个按钮后如何启用按钮 jQuery.
- 在带有弹出窗口的循环中创建一个按钮-jQuery Mobile
- 将下拉覆盖长度选择更改为按钮-jQuery DataTables
- 带有编辑按钮Jquery的待办事项列表
- 按钮jquery ui不工作
- 为函数赋值并在单独的按钮jquery上运行
- 检查表单数据值并禁用提交按钮jQuery表单
- 将鼠标悬停时的按钮替换为另一个不起作用的按钮jQuery
- "打开“;切换按钮jQuery
- 在单击按钮 Jquery 时验证表单
- UL LI元素在单击向上和向下按钮jQuery时自动滚动