簡體   English   中英

如何通過javascript找出div的內容?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM