我有一个div
<div id="mainDiv" onclick="devide(this.id, event);" style="z-index:1;position:relative; width:400px; height:400px; border:1px red solid;"></div>
点击它我会附加更多的div并希望同样的事情发生在他们身上,意味着在那里再点击2个divs shud b添加到他们
点击mainDiv mainDiv -mainDiv0 -mainDiv1
点击mainDiv0 mainDiv -mainDiv0 -mainDiv00 -mainDiv01 -mainDiv1
我想我能够清除事情
我使用了以下js
function devide(id, evt){
alert(id);
var divElement = document.getElementById(id);
if(typeof(divElement) != "undefined" && divElement!=null){
captureMousePosition(evt);
if(splitVertical==1)
verticalSplit(divElement);
else
horizontalSplit(divElement);
}
}
function verticalSplit(divElement){
divElement.style.border = "0px red dashed";
// divElement.removeAttribute("onclick");
var width = ((divElement.offsetWidth-(xMousePos-LEFT_MARGIN))/divElement.offsetWidth)*100;
var newDiv1 = document.createElement("div");
newDiv1.setAttribute("id", divElement.id+"0");
// newDiv1.onclick = "devide('"+divElement.id+"0', event);";
newDiv1.style.width = (100-width)+"%";
newDiv1.style.height = "100%";
newDiv1.style.float = "left";
newDiv1.style.border = "1px red dashed";
newDiv1.style.zIndex = divElement.style.zIndex+1;
var newDiv2 = document.createElement("div");
newDiv2.setAttribute("id", divElement.id+"1");
newDiv2.style.width = width+"%";
newDiv2.style.height = "100%";
newDiv2.style.float = "left";
newDiv2.style.border = "1px red dashed";
newDiv2.style.zIndex = divElement.style.zIndex+1;
divElement.appendChild(newDiv1);
divElement.appendChild(newDiv2);
newDiv1.addEventListener("click",devide(divElement.id+"0", event),true);
newDiv2.addEventListener("click",devide(divElement.id+"1", event),true);
}
但这是递归调用第一个遇到的元素的devide函数,例如mainDiv0,mainDiv00,mainDiv000 ....等等
请帮我解决这个问题
答案 0 :(得分:2)
您所描述的情况称为event bubbling。
W3C模型说您可以在活动上致电.stopPropagation()
。 IE可能需要window.event.cancelBubble
使用您的代码执行unobtrusive javascript尝试:
<强> HTML 强>
<div id="mainDiv"></div>
<强> JS 强>
function devide(evt){
var divElement = document.getElementById(this.id);// this.id !
if(typeof(divElement) != "undefined" && divElement!=null){
captureMousePosition(evt);
if(splitVertical==1)
verticalSplit(divElement);
else
horizontalSplit(divElement);
}
}
document.getElementById('mainDiv').onclick=devide; // notice it's just the function name
答案 1 :(得分:1)
关于这些行:
var divElement = document.getElementById(id);
if(typeof(divElement) != "undefined" && divElement!=null){
typeof 是一个运算符,而不是一个函数,因此不需要后跟分组运算符()。
更重要的是,测试的第一部分是不必要的,第二部分可以简化为:
if (divElement) {
如果文档对象不存在,或者不支持 getElementById ,则第一行将导致脚本错误并停止执行。如果第一行成功执行,则 divElement 将是对DOM元素的引用或 null (根据W3C DOM Core规范)。
鉴于上述情况,如果 divElement!= null 返回true,则 typeof divElement!='undefined'必须返回true(因为 divElement 不能定义,即使它是, undefined == null ),反之亦然,所以它是多余的。如果需要进行明确的测试(并且很少),那么:
if (divElement !== null) {
应该使用。