2014-06-16 59 views
3

我像這樣克隆我的mainSection(我必須克隆它,因爲有新元素添加到#main over AJAX,我不想通過它們進行搜索) :克隆一個元素後,找到文檔中的原始元素

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

然後我通過一個元素克隆的主要部分搜索:

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

當我找到字符串中的#mainSection「測試」我想從它那裏得到的原始元素在$ mainSection,所以我可以滾動到它通過:

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

問題是:我如何獲得$ foundElementOriginal?

+0

什麼是你的問題..?目前的結果是什麼? –

+0

目前我只是在克隆的mainSection中找到searchTermHtml ='test',我需要從此克隆元素中獲取對頁面中原始元素的引用。克隆的元素總是offset()。top = 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> 
+0

這個工程!但我不確定這是否是最佳解決方案。我的#main部分可以超過50 MB!在我正在測試的文檔中,我有9000個數據原始位置索引,並且性能非常好。所以我覺得這很好。非常感謝你! (而不是寫入:.attr(「數據原始位置」),寫入.data(「原始位置」)) –

+0

@ user3181141:如果分配屬性,那麼最好用'檢索它。 attr(「data-original-position」)',而不是'data(「original-position」)',除非由於其他原因使用'data'功能。 'data'不是**只是'data- *'屬性的一個訪問器; jQuery比底層的工作做得更多。現在,如果您根本不使用屬性*(通過執行$(this).data(「original-position」)來分配,然後使用'.data(「original-position」)')進行檢索,這很好,但是你不能在DOM檢查器中檢查這些值(因爲它們不是屬性)。 –

+0

我明白你的觀點。當我嘗試這種方法時,我不能使用:'$(「#main * [data-original-position =」+ originalPos +「]」)'來檢索原始元素。我試過這樣的:'$(「#main *」)。data(「pos,[」+ originalPos +「]」)'但是這不起作用。 –