我像这样克隆我的 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/