javascript - 我怎样才能用javascript找出一个div中的div?

标签 javascript dhtml html

我有一个页面,其中包含 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/

相关文章:

javascript - 如果输入为空则添加类,如果不为空则删除它

javascript - 如何在 vue.js 中根据父级选择 json 项目

javascript - 将一个数组项调用到另一个数组中

javascript - 更改 textNode 值

javascript - 使用 JavaScript 将值放入动态生成的输入类型中

javascript - Laggy 淡入淡出背景

javascript - id下自定义selectmenu jquery

html - 向左浮动被阻塞且未与左对齐

javascript - html - 选择范围 - 获取范围+起始节点+结束节点+距离

html - 背景图片不会用 HTML/CSS 显示