javascript - 克隆元素后在文档中找到原始元素

标签 javascript jquery clone

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

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

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

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

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

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

问题是:如何获得 $foundElementOriginal?

最佳答案

由于您在克隆后更改 #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>

关于javascript - 克隆元素后在文档中找到原始元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24239550/

相关文章:

javascript - jQuery 克隆形式增加名称、类、ID、数据 ID 等所有属性

javascript - 如何在javascript中计算数组中的重复值

javascript - 从 HTML 元素(例如 onclick 处理程序)调用 RequireJs 模块中的方法

javascript - 制作图片作为链接

jquery - Event.preventDefault() 在所有浏览器上的 Jquery 中失败

c# - FormatterServices.GetUninitializedObject 如何在内部工作?

javascript - 在 JavaScript ES6 中,我如何只从散列中获取一些属性?

javascript - jQuery Ajax 登录中没有 'Access-Control-Allow-Origin' header

javascript - 如何从异步调用返回响应?

正常运行时 jQuery 代码不起作用。但我确实激活了断点