我正在创建用于数据输入的HTML表单,其中包含几个文本框和功能按钮。
还有一个添加按钮,可为每个“行”从DIV模板(id:w)复制(克隆),并附加到主DIV的末尾(id:t)。在每一行上,都有一个“ X”按钮来删除该行,以及两个箭头按钮以在DOM中可视地上下移动“行”。
该表单是从数据库和页面加载时并使用JQuery 3.4.1时已在页面上的元素动态创建的,用于使用每行按钮的功能进行选择和大多数DOM操作。
将“行”添加到容器DIV中,然后根据期望的计数器重命名元素。 “ X”按钮删除“行”,并在容器DIV中上下移动所有现有行。
但是由于某些未知原因,必须创建两次新行,然后按两次“向上”按钮。最下面一行的“向下”按钮是多余的,不起作用。
我认为这可能与前一个Sibling和NextSibling返回错误的Object类型并导致问题并首次失败有关。
关于如何修复或改进此功能的想法?
谢谢。
var rr = $("[id^=l]").length;
$(".data-up").click(function() {
var e = $(this).first().parent().parent().get(0);
moveUp(e);
});
$(".data-down").click(function() {
var e = $(this).parent().parent().get(0);
moveDown(e);
});
$(".remove").click(function() {
$(this).parent().parent().remove();
});
function add() {
rr += 1;
var a = $("#w").clone(true, true).removeAttr('id').removeAttr('style');
a.attr("datarow", "row" + rw);
a.find("input[data-field='l']").attr("id", "l" + rr).attr("name", "l" + rr).removeAttr("data-field");
a.find("input[data-field='s']").attr("id", "s" + rr).attr("name", "s" + rr).removeAttr("data-field");
a.appendTo("#t");
}
function moveUp(e) {
if (e.previousSibling) {
if (e.previousSibling === e.parentNode.children[0]) {} else {
e.parentNode.insertBefore(e, e.previousSibling);
}
}
}
function moveDown(e) {
if (e === e.parentNode.children[e.parentNode.children.length - 1]) {} else {
e.parentNode.insertBefore(e.nextSibling, e);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" ID="p" onclick="add();">Add</button>
<div id="t">
</div>
<div class="form-group row" id="w" style="display:none;" datarow="row">
<div class="col-sm-1"><input name="s" class="form-control txt-s col-form-label" id="s" type="text" readonly="true" data-field="s"></div>
<div class="col-sm-3"><input name="l" class="form-control txt-l" id="l" type="text" data-field="l"></div>
<div class="col-sm-2">
<button class="btn btn-danger mr-1 remove" type="button">X</button>
<button class="btn btn-info mr-1 data-up" type="button">↑</button>
<button class="btn btn-info data-down" type="button">↓</button>
</div>
</div>
使用jQuery-使用.closest()
查找按钮的当前父级。查找.closest()
或.prev()
兄弟。如果存在同级,请使用.prev()
或.next()
在同级之前或之后移动当前父级:
.next()
.insertBefore()