[英]How can I find out what div a div is in with javascript?
我有一个页面,其中包含4个带ID的静态div。 我将添加scriptaculous可拖动和可放置效果,以允许通过将许多动态生成的div从一个div移动到另一个div来进行交互。
我需要能够找出动态div所在的静态div。我如何获得这些信息?
上面的评论者注意脚本的方法来做到这一点,但总是值得知道如何在没有拐杖的情况下以这种方式执行基本的DOM操作。 此代码未经测试,但肯定非常接近您想要使用的代码:
/**
* Finds the ancestor div element of descendantDiv which has one of
* the given array of ids. If multiple div elements have with the
* given ids are ancestors of descendantDiv, the most closely related
* one (i.e. parent preferred to grandparent) is returned. If no
* ancestor of descendantDiv is a div element with one of the ids
* given by ids, returns null.
*
* @param descendantDiv : HTMLDivElement
* the div element whose containing div with one of the provided
* ids is to be determined
* @param ids : [string]
* array of ids which the desired ancestor div might have
* @returns HTMLDivElement
* the first parent, grandparent, etc. div element of descendantDiv
* which has an id contained in ids
*/
function findAncestorDivWithId(descendantDiv, ids)
{
for (var parent = descendantDiv.parentNode;
parent;
parent = parent.parentNode)
{
if (parent.nodeName.toLowerCase() !== "div")
continue;
for (var i = 0, sz = ids.length; i < sz; i++)
{
if (parent.id === ids[i])
return parent;
}
}
return null;
}
由于您计划使用Scriptaculous,因此您可以使用Prototype轻松完成此操作:
if ($("dynamicElement").descendantOf("staticElement"))
{
}
据我了解你的问题,你想找到一个已知元素的所有孩子(或所有孩子的div)?
当您使用scriptaculous时,您可以使用原型中的childElements方法。 有关详细信息,请参阅http://prototypejs.org/api/element/childElements 。
欢迎来到stackoverflow。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.