[英]What's wrong with my attempt to remove an element with JavaScript?
我有一个使用以下系统的表单:字段及其标签是float: left
,解释如何填充字段的扩展注释显示在右侧,位置很靠左。
按照Eric Meyer的书中的建议,我使用hr来使两者对齐:我将hr
样式设置为:
.lineup { clear:both; visibility: hidden}
然后,使用Javascript在需要时显示评论。
这非常有用,除了(对于Safari中的一些怪异问题)以及注释真的很长,当它“按下”出现的其他表单内容时。
因此,我说过,我可以编写一个Javascript函数在页面构建上运行,删除hr(记住它们的offsetTop)并将所有描述移动到hr所在的位置。
但是我无法删除它。
最后的代码:
var hrListY = new Array(); // Y-coordinates of HR "lineup" elements
// Moves all descriptions so their middle is where the top used to be, and
// removes the <hr>s previously used to position them.
function relayoutDescriptions() {
var hrs = document.getElementsByTagName("hr");
alert('hrs.length = ' + hrs.length);
var i;
for (i = 0; i < hrs.length; i++) {
var hr = hrs[i];
if (hr.className == 'lineup') {
hrListY.push(hr.offsetTop);
alert('Got an HR element: Y = ' + hr.offsetTop + ' parentNode class = "' + hr.parentNode.className + '"');
hr.parentNode.removeChild(hr);
}
}
// Now we have a list of Y-coordinates of HR elements, hrListY. We use it
// to adjust the offsetTop's of the -desc divs. For each one, we adjust the
// offsetTop so the center of the div is at the height where the HR was.
}
到目前为止,这就是我所拥有的。 它为我提供了offsetTop的合理升序数字和一个合理的父节点类,但是生成的布局清楚地显示出了,萤火虫确认,hr仍然存在。
救命?
聚苯乙烯
如果可以使用JQuery轻松实现此目的,那么我很满意,但是我真的很想知道$ @#&*%在这里发生了什么。
谢谢!
由getElementsByTagName
返回的节点列表是活动的,这意味着当您从DOM中删除其元素之一时,向右移动的对象将向左移动,因此,您仅删除了第二个项目。
从http://www.w3.org/TR/DOM-Level-2-Core/core.html
DOM中的NodeList和NamedNodeMap对象是活动的; 也就是说,对基础文档结构的更改将反映在所有相关的NodeList和NamedNodeMap对象中。
您可以通过移动alert('hrs.length = ' + hrs.length);
在你的循环中。 每次提醒都会有不同的号码。
要解决此问题,您可以复制列表
var myNodeList = document.getElementsByTagName('HR');
myNodeList = Array.prototype.slice.call(myNodeList);
或者您可以从右向左迭代
var myNodeList = document.getElementsByTagName('HR');
for (var i = myNodeList.length; --i >= 0;) {
...
}
这样,当您删除某项时,右侧没有任何内容会向左移动,从而使您的索引混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.