对于Loop/Each Loop变量存储和比较(jQuery或Javascript
For Loop/Each Loop variable storage and comparison (jQuery or Javascript
我有一个带有jquery的each循环(如果代码运行得更好,我不介意使用for循环),它使用class="searchMe"在所有div中循环。我想把当前div存储在一个变量中,我可以在循环的下一次迭代中使用这个变量来比较一个值和新的当前div。为了简化事情,删除了一些代码(全部有效),但下面是我的代码:
$('.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行外,一切都正常。通过each/for循环,这可能吗?
我不知道当您单独进行向后比较时,为什么需要进行排序。你可以将最后三行替换为。。。
if ( parseInt(id.attr("name")) > parseInt(id.prev().attr("name")) ) {
id.insertBefore(id.prev()).remove();
}
您可以在$.each()
中使用index
像
$('.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()
相关文章:
- jQuery setTimeOut: in for-loop
- Coffeescript jQuery each loop
- jquery .change inside loop
- for loop inside another for loop javascript (jquery)
- setTimeout in jQuery with a loop
- (jQuery)foreach-loop 内的选项卡 ->一个页面上多个选项卡的问题
- jQuery - End setInterval Loop
- jQuery Bounce: Bounce, delay, loop
- jQuery $.each loop and json mysql data
- jQuery each function parseInt loop
- Jquery Document.ready loop
- Javascript jquery fade-in/fadeout loop,如何使用计时器
- Laravel foreach loop with jquery slidetoggle
- Loop jQuery for each child
- jQuery Stop fadeOut/fadeIn Loop
- jQuery Image Load Loop - Wrap HTML & Check Size?
- jQuery append in loop - DOM 直到最后才更新
- jQuery.animate() in a for loop
- 如何在 JavaScript for loop 中使用 jQuery “autocomplete source”
- Jquery-On click changing loop