0

childNode現在、要素のを選択しようとしています。これが私がそうしようとしている方法です:

var postBody_elem = elem.parentNode.parentNode.childNodes['post'].childNodes['postBody'];

私も試しました:

elem.parentNode.parentNode.childNodes[0].childNodes[1];

私はそれが、childNodesではなく、の問題であることを知っていparentNodesます。私はテストしました。

これは私がしていることの単純化された構造です:

<section id = 'postWrapper'>                          //This is the Second Parent.
  <article id = 'post'>                               //This should be the First Child.
    <section id = 'postInfo'>
      <section id = 'postTitle'></section>
      <section id = 'poster'></section>
      <section id = 'postDate'></section>
    </section>
    <section id = 'postBody'>                       //This should be the Second Child.
    </section>
  </article>
  <section id = 'postBar'>                          //This is the First Parent.
    <img id = 'portrait'>
    <section id = 'editButton'>Edit</section>       //This is the var elem.
    <section id = 'deleteButton'>Delete</section>
  </section>
</section>

親ノードと子ノードをナビゲートして参照する必要が'postBody'ある理由は、この形式が何度も繰り返されるためです。

-これで問題が発生します。上記のコード行はGoogleChromeでは機能しますが、FireFoxでは機能しません。さまざまなバリエーションを試しましたが、コンソールで未定義のエラーが表示されます。要素が適切に記述されていることを確認しました。これは、ブラウザがそれを処理する方法の違いにすぎないと思います。

誰かが答えを持っているなら、私が示した要素をどのように参照できるかについてであり、id複数の要素を不適切に使用した方法についての講義ではありません。これはこの場合は問題ではないためです(私の知る限り) 、Chromeで動作するため)。

ありがとう。

4

2 に答える 2

1

後世のためのいくつかの選択肢(これらはFirefoxで動作しますが、他のブラウザでのサポートについてはわかりません):

  1. elem.childrenテキストノードを除外するので、elem.parentNode.parentNode.children[0].children[1]うまくいくでしょう

  2. 使用できますelem.parentNode.parentNode.getElementsByTagName('section')[4](0 = postInfo、1 = postTitle、2 = poster、3 = postDate)

  3. あなたはelem.parentNode.parentNode.querySelector('article > section + section')例えば使うことができます

  4. elem.parentNode.previousElementSibling.lastElementChildもうまくいくと思います

于 2012-12-05T11:45:36.500 に答える
1

最初の方法は非標準のように見えるためFirefoxでは機能しません。2番目の方法は、childNodeもテキストノードで構成されていることに気づかなかったため機能しません。必要な要素を取得するには、

elem.parentNode.parentNode.childNodes['1'].childNodes['3']

http://jsfiddle.net/mowglisanu/UqZVn/

于 2012-12-05T04:48:48.680 に答える