2013-08-01 184 views
0

我用jQuery的每個循環(我不介意使用for循環,如果代碼工作更好),它的循環通過與類的所有div =」 searchMe「。我想將當前的div存儲在一個變量中,我可以在循環的下一次迭代中使用它來比較一個值和新的當前div。有些代碼被刪除(所有工作)以簡化事情,但這是我的代碼:For循環/每個循環變量的存儲和比較(jQuery的或Javascript

$('.searchMe').each(function(){ 
    var id = $(this); 
    sortUp += 1, 
    sortDown -= 1; 

    if (test) { 
    id.attr("name", ""+sortUp+""); 
    } 
    else { 
    id.attr("name", ""+sortDown+""); 
    } 

    if (id.attr("name") > lastId.attr("name")) { 
    id.insertBefore(lastId); 
    } 
    lastId = id; //this doesn't work, but illustrates what I'm trying to do 
}); 

一切除了最後3行正常工作 這可能與每個/ for循環

+0

'lastId'的作用域是什麼? –

回答

2

我不知道爲什麼樣了,需要你的時候單獨進行倒退比較。你可以用最後三行代替...

if (parseInt(id.attr("name")) > parseInt(id.prev().attr("name"))) { 
id.insertBefore(id.prev()).remove(); 
} 
+0

什麼是性感的答案! – EmmaGamma

2

可以用0?在$.each()

$('.searchMe').each(function(index){ 
    var id = $(this); 
    sortUp += 1, 
    sortDown -= 1; 
    if (test) {// don't know what is test, let it is predefined 
    id.attr("name", sortUp);// no need to add "" 
    } 
    else { 
    id.attr("name", sortDown); 
    } 
    if ($('.searchMe').eq(index-1).length && id.attr("name") > $('.searchMe').eq(index-1).attr("name")) { 
    id.insertBefore($('.searchMe').eq(index-1)); 
    } 
}); 

或者或者可以define lastid

var lastId='';// let it be global 
$('.searchMe').each(function(index){ 
    var id = $(this); 
    sortUp += 1, 
    sortDown -= 1; 
    if (test) {// don't know what is test, let it is predefined 
     id.attr("name", sortUp);// no need to add "" 
    } 
    else { 
     id.attr("name", sortDown); 
    } 
    if (id.attr("name") > lastId.attr("name")) { 
     id.insertBefore(lastId); 
    } 
    lastId=id;// assign here the current id 
}); 

閱讀eq()$.each()

+0

我真的非常感謝他,我打算用rps的答案去做,因爲代碼更短,甚至將它設置爲全局變量不起作用。 – EmmaGamma