我试图移除一行''在' del4'之后带有查询的div选择按钮,然后重命名剩余行div中的所有输入。要重命名剩余行div中的输入,我想循环遍历“可排序”的子项。格。
我可以在删除行div之前找到可排序的div,但在删除行后无法找到可排序的div。
HTML:
<div class="sortable ui-sortable" id="AutostationCLEAR">
<div class="row">
<div class="col-md-1"><div class="col-md-6"><p><strong><input type="hidden" name="state_id0" value="0">1.</strong></p></div><div class="col-md-6"><p class="text-muted"><span class="glyphicon glyphicon-align-justify"></span></p></div></div>
<div class="col-md-6"><p><input type="text" class="form-control" name="stateName0" placeholder="State"></p></div>
<div class="col-md-2"><p><input type="checkbox" class="form-control" name="occupied0" value="1"></p></div>
<div class="col-md-2"><p><input type="checkbox" class="form-control" name="clear0" value="1"></p></div>
<div class="col-md-1"><p><button type="button" class="btn btn-danger btn-sm del4" id="0"><span class="glyphicon glyphicon-remove"></span></button></p></div>
</div>
<div class="row">
<div class="col-md-1"><div class="col-md-6"><p><strong><input type="hidden" name="state_id1" value="">2.</strong></p></div><div class="col-md-6"><p class="text-muted"><span class="glyphicon glyphicon-align-justify"></span></p></div></div>
<div class="col-md-6"><p><input type="text" class="form-control" name="stateName1" placeholder="State"></p></div>
<div class="col-md-2"><p><input type="checkbox" class="form-control" name="occupiedundefined" value="1"></p></div>
<div class="col-md-2"><p><input type="checkbox" class="form-control" name="clear1" value="1"></p></div>
<div class="col-md-1"><p><button type="button" class="btn btn-danger btn-sm del4" id="1"><span class="glyphicon glyphicon-remove"></span></button></p></div>
</div>
</div>
JQuery的:
$(document).on('click','.del4',function(){
alert($(this).closest(\".sortable\").attr('id')); \\shows sortable div id as expected
$(this).closest(\".row\").remove(); \\remove the row
alert($(this).closest(\".sortable\").attr('id')); \\no longer shows sortable div id
});
任何帮助将不胜感激!
答案 0 :(得分:2)
由于您已从dom树中删除了包含当前元素的row
,因此当前元素不再出现在dom树中,因此它将无法找到sortable
元素。
因此,您需要在删除行之前获取最接近sortable
的引用
$(document).on('click', '.del4', function () {
var $sortable = $(this).closest('.sortable');
alert($sortable.attr('id')); //shows sortable div id as expected
$(this).closest('.row').remove(); //remove the row
//do further processing using $sortable here
});
演示:Fiddle
答案 1 :(得分:0)
尝试初始缓存最近的元素,就像其他专家建议的那样。
$(document).on('click','.del4',function(){
var cache = $(this).closest('.sortable');
$(this).closest(".row").remove();
alert(cache.attr('id'));
});