[英]JQuery Javascript for loop stops after first iteration
I have two <ul>
lists, and I want to move a selected element from one to another after checking if it already exists in the destination list, so I had to create a function that compares the text of the the selected <li>
with the <li>
elements n the destination <ul>
: 我有两个<ul>
列表,我想在检查目标列表中是否已存在某个选定元素之后将其从一个移到另一个,因此我不得不创建一个函数,该函数将选定的<li>
的文本与目标<ul>
的<li>
元素:
$(document).ready(function () {
$('html').on('click', 'li', function() {
$(this).toggleClass('selected');
});
//Déplacer vers la gauche
$('#btnLeft').click(function() {
var elementExiste = function(liste,selectionne){
var exists=false;
for(var x=0; x<liste.length; x++){
if(liste.children().eq(x).text()===selectionne){
exists=true;
break;
}
}
return exists;
}
var bool = true;
for(var i=0; i< $('.selected').length; i++){
if(elementExiste($('.list1'),$('.selected').eq(i).text())){
alert('Cet élément existe déjà');
bool = bool && false;
}
else {
bool = bool && true
}
}
if(bool)
$('.list1').append($('.list2 .selected').removeClass('selected'));
});
}
The for loop works fine for the first iteration, but it just breaks after this for循环在第一次迭代中工作正常,但是在此之后就中断了
You pass ul to the function so liste.length = 1 You could pass all li elements: 您将ul传递给函数,因此liste.length = 1您可以传递所有li元素:
elementExiste($('.list1 li'),$('.selected').eq(i).text()))
or pick li elements inside: 或在其中选择li元素:
liste.children().length
so it could iterate through all of them. 这样就可以遍历所有这些对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.