我有一个页面,其中包含4个带ID的静态div。我将添加scriptaculous可拖动和可放置效果,通过将许多动态生成的div从一个div移动到另一个div来允许交互。
我需要能够找出动态div所在的静态div。我如何获得这些信息?
答案 0 :(得分:3)
上面的评论者注意脚本执行此方法,但总是值得知道如何在没有拐杖的情况下以这种方式执行基本的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;
}
答案 1 :(得分:1)
由于您计划使用Scriptaculous,因此您可以使用Prototype轻松完成此操作:
if ($("dynamicElement").descendantOf("staticElement"))
{
}
答案 2 :(得分:0)
据我了解你的问题,你想找到已知元素的所有孩子(或所有孩子的div)?
当您使用scriptaculous时,您可以使用原型中的childElements方法。 有关详细信息,请参阅http://prototypejs.org/api/element/childElements。
欢迎来到stackoverflow。