[英]JavaScript change for-loop condition while looping (No JQuery)
I have a code that looks kinda like this. 我有一个看起来像这样的代码。
And what i want to achive is to change the for loop codition if the div that is checked has child divs. 我要实现的是如果检查的div有子div,则更改for循环条件。
var condition = divs.querySelectorAll('div');
for(i = 0; i < condition.length; i++){
if(condition[i].querySelectorAll('div').length > 0){
condition = condition[i].querySelectorAll('div');
i = 0;
}else{
// Last div reached.
break;
}
}
Does anyone out there know how to achive this effect. 有没有人知道如何达到这种效果。 Do i have to use an other type of loop?
我是否必须使用其他类型的循环?
EDIT: 编辑:
Since it seems i was wrong about what code was wrong, i now post my messy piece of code: 由于似乎我错了什么代码是错误的,所以现在发布我凌乱的代码:
var posX = e.clientX;
var posY = e.clientY;
function mouseDown(e){
var getChildDivs = this.querySelectorAll('div');
if(getChildDivs.length > 0){
var offsetDivLeft = 0;
var offsetDivTop = 0;
for(i = 0; i < getChildDivs.length; i++){
if(posX >= getChildDivs[i].offsetLeft && posX <= getChildDivs[i].offsetLeft + Math.floor(getChildDivs[i].style.width.slice(0, -2)) &&
posY >= getChildDivs[i].offsetTop && posY <= getChildDivs[i].offsetTop + Math.floor(getChildDivs[i].style.height.slice(0, -2))){
if(getChildDivs[i].querySelectorAll('div').length > 0){
offsetDivLeft = offsetDivLeft + getChildDivs[i].offsetLeft;
offsetDivTop = offsetDivTop + getChildDivs[i].offsetTop;
getChildDivs = getChildDivs[i].querySelectorAll('div');
curDiv = getChildDivs[i];
i = 0;
}else{
curDiv = getChildDivs[i];
break;
}
}
}
}
}
i created a fiddle which loops over every child element and children of children as well: 我创建了一个小提琴,它遍历了每个孩子元素以及孩子的孩子:
http://jsfiddle.net/czzeaz3x/ http://jsfiddle.net/czzeaz3x/
var condition = divs.querySelectorAll('div');
for(i = 0; i < condition.length; i++){
if(condition[i].children.length > 0){
condition = condition[i].querySelectorAll('div');
alert(condition);
i = 0;
}else{
// Last div reached.
break;
}
}
i hope it helps ;) 我希望它会有所帮助;)
The correct solution is 正确的解决方案是
function mouseDown(e){
curdiv = e.target;
}
The target
property of the event gives you the actual div which was clicked--normally the frontmost one, which is also normally the most deeply nested one. 事件的
target
属性为您提供了实际单击的div,通常是最前面的div,通常也是嵌套最深的div。 From MDN : 从MDN :
A reference to the object that dispatched the event.
对调度事件的对象的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.