克隆元素后,找到文档中的原始元素

时间:2014-06-16 08:36:22

标签: javascript jquery clone

我像这样克隆我的mainSection(我必须克隆它,因为在AJAX上添加了#main的新元素,我不想搜索它们):

$mainSection = $('#main').clone(true);

然后我在克隆的主要部分中搜索元素:

var searchTermHtml = 'test';
$foundElement = $mainSection.filter(":contains('"+searchTermHtml+"')");

当我找到字符串' test'在#mainSection中我想从$ mainSection中获取原始元素,所以我可以通过以下方式滚动到它:

var stop = $foundElementOriginal.offset().top;
window.scrollTo(0, stop);

问题是:我如何获得$ foundElementOriginal?

1 个答案:

答案 0 :(得分:2)

由于您在克隆它之后更改了#main的内容,因此使用结构化内容(子元素在其父元素中等)将不可靠。

在克隆它之前,您需要在#main 中的元素上添加某种标记,以便稍后可以使用这些标记来关联您找到的克隆元素到#main中的原始元素。您可以通过向其添加data-*属性来标记所有元素,但是如果您对实际问题域有了更多的了解,我希望您可以避免那么挥霍。

以下是一个完整的示例:Live Copy

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <meta charset="utf-8">
  <title>Example</title>
</head>
<body>
  <div id="main">
    <p>This is the main section</p>
    <p>It has three paragraphs in it</p>
    <p>We'll find the one with the number word in the previous paragraph after cloning and highlight that paragraph.</p>
  </div>
<script>
  (function() {
    "use strict";

    // Mark all elements within `#main` -- again, this may be
    // overkill, better knowledge of the problem domain should
    // let you narrow this down
    $("#main *").each(function(index) {
      this.setAttribute("data-original-position", String(index));
    });

    // Clone it -- be sure not to append this to the DOM
    // anywhere, since it still has the `id` on it (and
    // `id` values have to be unique within the DOM)
    var $mainSection = $("#main").clone(true);

    // Now add something to the real main
    $("#main").prepend("<p>I'm a new first paragraph, I also have the word 'three' but I won't be found</p>");

    // Find the paragraph with "three" in it, get its original
    // position
    var originalPos = $mainSection.find("*:contains(three)").attr("data-original-position");

    // Now highlight it in the real #main
    $("#main *[data-original-position=" + originalPos + "]").css("background-color", "yellow");

  })();
</script>
</body>
</html>