javascript - jQuery获取元素的先前位置
问题描述
我正在寻找一种方法来找出元素之前的位置append
,我有 50 个元素应该附加到不同的元素,但是在某个语句中,问题是如何找到每个元素的先前位置?
$('#statment').change(function() {
var val = $(this).val();
if (val === "0") {
$('#text1').appendTo('#target');
$('#text2').appendTo('#target');
} else if (val === "1") {
$('#text1').appendTo('#old');
$('#text2').appendTo('#old');
// Detect previous place??
}
});
#target {
padding: 10px;
border: 1px dashed red;
width: 200px;
margin-top: 10px;
}
#old {
padding: 10px;
border: 1px dashed blue;
width: 200px;
margin-top: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="statment" type="number" value="1" min="0" max="1" />
<div id="target"></div>
<div id="old">
<a id="text1">Text 1</a>
<a id="text2">Text 1</a>
</div>
这只是我的真实代码示例,真实代码太大,无法分享。
我需要else
检测每个元素的先前位置,而不是将每个元素带回旧父级。可能吗?
$('#text1').appendTo('#target');
那么我怎样才能找到这个元素的原点位置呢?
解决方案
一种方法是在将元素移离原始位置时在原始位置留下“痕迹”。<span>
就像一个具有引用该元素的属性的空对象。
这是如何工作的:
$('#statment').change(function() {
var val = $(this).val();
if (val === "0") {
$('#text1,#text2').each(function () {
// Only move the element when it is not yet within the target area
if (!$(this).closest("#target").length) {
$(this).wrap($('<span>').attr("data-ref", this.id)).appendTo('#target');
}
});
} else if (val === "1") {
$('span[data-ref]').each(function () {
$(this).replaceWith($('#' + $(this).data("ref")));
});
}
});
#target {
padding: 10px;
border: 1px dashed red;
width: 200px;
margin-top: 10px;
}
.old {
padding: 10px;
border: 1px dashed blue;
width: 200px;
margin-top: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="statment" type="number" value="1" min="0" max="1" />
<div id="target"></div>
<div class="old">
<a id="text1">Text 1</a>
</div>
<div class="old">
<a id="text2">Text 2</a>
</div>
推荐阅读
- vue.js - 当语言模式设置为 Vue 时,样式 Intellisense 在 VS Code 中不起作用
- python - 是否可以将 django-cryptography 与 filter 或 get 方法一起使用?
- html - 将最后一个孩子放在前一个孩子旁边 - Flexbox
- r - 从 ks 包绘制 kde.local.test 结果时,fhat 评估点的误差单调增加
- api - 通用 Windows 平台上的 User32 Windows UI Api
- java - 将谷歌地图添加到底部导航栏的按钮
- list - 检查连续元素之间的差异是否相同
- matlab - 为什么在 MATLAB 中允许使用多个连续的加号语法?
- mysql - 运行查询统计
- c# - Dbcontext 的构造函数不断更改模型更新的基本参数