首页 > 解决方案 > 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');那么我怎样才能找到这个元素的原点位置呢?

标签: javascriptjqueryhtml

解决方案


一种方法是在将元素移离原始位置时在原始位置留下“痕迹”。<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>


推荐阅读