2011-07-25 28 views
1

我使用.each()来遍历jQuery对象$firstParagraph中的链接。在遍历链接时,我想以绝对的方式引用它们,而不调用$(this),每次调用它时都会创建一个新对象。因为当我在链接上单独遍历两次(如下面的代码所示)时,两个实例中完成的工作并未结合。

$firstParagraph = $("p").eq(0); 

// Iterate over the links once 
$firstParagraph.find("a").each(function() 
    { 
     $this = $(this); 
     // Modify $this 
    }); 

// Iterate over the links a second time 
$firstParagraph.find("a").each(function() 
    { 
     $this = $(this); 
     // I want to modify $this again, but without loosing 
     // the work I did in the first iteration 
    }); 
+1

你不应该修改'$(this)'。你想做什么? – SLaks

+0

你在修改什么? – Sparkup

+2

为什么不把两个逻辑结合在一个循环中? – ShankarSangoli

回答

4

而不是像你问的那样对付jQuery的暴力,让我告诉你如何去做你实际需要做的事情:使用$(this).data('somekey', someval)$(this).data('somekey')来代替直接修改$(this)作为一个对象,无论您想要做什么,都可以将数据附加到您的$(this)概念上,以便您能够恢复原状。 (文档here。)

+0

这听起来很有希望。非常感谢! – Randomblue

+0

@Randomblue:没问题。 :) – chaos

0

你可以做这样的事情:

var elemArray = []; 
// Iterate over the links once 
$firstParagraph.find("a").each(function(i) 
    { 
     $this = $(this); 
     elemArray[i] = $this; 
     // Modify $this 
    }); 

// Iterate over the links a second time 
$firstParagraph.find("a").each(function(i) 
    { 
     $this = elemArray[i]; 
     // I want to modify $this again, but without loosing 
     // the work I did in the first iteration 
    }); 

我不知道这是否是因为东西可以在两个环路之间改变是个好主意。

1

为什么不追加到Array?当你使用简单的变量时,它会一直覆盖它。

相关问题