javascript,无法检索兄弟节点
我已经这样做有一段时间了,但我似乎无法破解它。除了通过函数传递的那个之外,我还有一些 javascript 试图隐藏同级 div。这是 html:
<div id = "chat_content">
<div id = "chat_content_1">This is div one</div>
<div id = "chat_content_2">This is div two</div>
<div id = "chat_content_3">This is div three</div>
</div>
这是 javascript:
function showGroup(id)
{
// show the the div that was clicked
var e = document.getElementById(id);
e.style.display = 'block';
// hide the others divs under the same parent
var children = e.parentNode.childNodes;
for (var i = 0; i < children.length; i++)
{
if (children[i] != e)
{
children[i].style.display = 'none';
}
};
}
谢谢!节日快乐:)
I've been at this for a while and I can't seem to crack it.. I have some javascript trying to hide sibling divs, besides the one that is passed through the function. Here's the html:
<div id = "chat_content">
<div id = "chat_content_1">This is div one</div>
<div id = "chat_content_2">This is div two</div>
<div id = "chat_content_3">This is div three</div>
</div>
And here's the javascript:
function showGroup(id)
{
// show the the div that was clicked
var e = document.getElementById(id);
e.style.display = 'block';
// hide the others divs under the same parent
var children = e.parentNode.childNodes;
for (var i = 0; i < children.length; i++)
{
if (children[i] != e)
{
children[i].style.display = 'none';
}
};
}
thanks! and happy holidays :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑使用 jQuery。让生活更轻松。
请查看此处
Consider using jQuery. Makes life easier.
Check it out here
您不使用
previousSibling
或nextSibling
是否有任何原因?你的代码理论上应该可以工作,但由于它显然不能工作(你检查过你的错误控制台吗?),请尝试以下使用迭代器思想而不是数组循环工作的方法:我同意使用 jQuery 之类的东西的建议顺便一提。它确实让事情变得更容易。
Is there any reason you're not using
previousSibling
ornextSibling
? Your code should work in theory, but since it apparently doesn't (have you checked your error console?), try the following which works using a sort of iterator idea rather than an array loop:I second the recommendation for using something like jQuery by the way. It does make things easier.