Pergunta

Im a jquery starter so if its a wrong one forgive me :)

I just want to know why placing the content at different positions made this script working, although to my best i think script to kept in head section of the document. Please explain the concept.

Working Code

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example 2</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

</head>

<body>

<p>
</p>

<script type="text/javascript">
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
</script>

</body>
</html>

Not Working

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example 2</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
</script>
</head>

<body>

<p>
</p>

</body>
</html>
Foi útil?

Solução

In the second instance the code is executed before the <p> has been parsed into the DOM tree, so while it still works there's nowhere to put the output text into. In other words, jQuery("p") matches no element so .html() "does nothing".

You can fix this by either waiting for the DOM to be fully parsed:

jQuery(function() {
    jQuery("p").html(...);
});

or by using an output mechanism that does not depend on the <p> existing, such as alert() or console.log().

Outras dicas

Well, it seems that your browser firstly load <head> section thus in second example there is no p element then.

In both cases you should wrap your code in $(function(){ ... }).

If you place your script before the <body> element, it is executed before the DOM tree is loaded/parsed. The <p> element does therefore not exist and cannot be found. You can:

  • Place the script after the <body> tag (like in your first example)

  • or you can call your function after the ready event has been fired:

    $(document).ready(function() {
      jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
    });
    
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top