Domanda

Please, read and try the code below. Click on "foo" paragraph. Looking at the browser console, I don't see the expected results, while if I click on "bar", I do.

Why is that happening?

<!DOCTYPE HTML PUBLIC
  "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
  </head>
  <body>
    <div class="root">
      <div>
        <p id="foo">foo</p>
      </div>
      <p id="bar">bar</p>
    </div>
    <script type="text/javascript">
      var p_list = document.getElementsByTagName('P');
      for (var n=0; n<p_list.length; n++) {
        p_list[n].onclick = function() {
          console.log('ONCLICK - id: ' + this.id + ' - ' + getC( this ) + '\n');
        };
      }
      function getC( P ) {
        if (P.parentNode.className === 'root') {
          console.log('INSIDE FUNCTION - id: ' + P.id + ' - ' + P.parentNode);
          return P.parentNode;
        } else {
          getC( P.parentNode );
        }
      }
    </script>
  </body>
</html>

Live code: http://jsbin.com/izuleg/1/edit

È stato utile?

Soluzione

You're just missing a return statement in your else clause. It should be:

...

} else {
    return getC( P.parentNode );
}

Note that you're using a recursive function (a function that calls itself), so you should probably add extra precautions to make it return something in exceptional cases (such as, there is no node with class "root"), otherwise you'll get an infinite recursion, and a stack overflow error.

Altri suggerimenti

Here is your mistake. You should return the result of getC instead of just calling it.

function getC( P ) {
    if (P.parentNode.className === 'root') {
      console.log('INSIDE FUNCTION - id: ' + P.id + ' - ' + P.parentNode);
      return P.parentNode;
    } else {
      return getC( P.parentNode );
    }
  }

You missed <div> and </div> tags, please check:

    <div class="root">
          <div>
            <p id="foo">foo</p>
          </div>
          <div>
            <p id="bar">bar</p>
          </div>
    </div>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top