我有一个页面,其中包含 4 个带 ID 的静态 div。我将添加脚本化的可拖放效果,以通过将许多动态生成的 div 从一个 div 移动到另一个 div 来实现交互。
我需要能够找出动态 div 位于哪些静态 div 中。我如何获得此信息?
最佳答案
上面的评论者注意到执行此操作的 Scriptaculous 方法,但了解如何在没有拐杖的情况下以这种方式执行基本的 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;
}
关于javascript - 我怎样才能用javascript找出一个div中的div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1250121/