ドキュメント

Talk:Tutorials:How jQuery Works

From jQuery JavaScript Library

Jump to: navigation, search

I'm having a strange problem with the first example in the tutorial. I created a simple html page, as per the instructions. I included the latest build of the jquery page and added the function that would create an alert box via a link click. Nothin. So, I added a JS "Hello world" function as an onload event to make sure that JS was working fine. Check. I double-checked that the Jquery include file was in the right place. Check. I tried the alert box function again. Nothin. So then I jumped ahead of the tutorial and just stole the jquery example from the jquery home page (i.e. revealed hidden paragraph) like this:

function test() {

 $("p.surprise").addClass("ohmy").show("slow");

}

And it worked! So clearly there is something wrong with this first alert function.

You can see for yourself here: http://www.troped.com/labs/jquery-basic.html

Maybe I've done something really boneheaded, but at this point I don't think so.

Enclose your code in $(document).ready()

Hi there,

You need to do one of two things to get your example working reliably. For one, you can enclose your alert script in the following block:

$(document).ready(function(){
   // Put your alert function here
 });

This code basically says "when the whole document is ready to be acted upon (i.e. when the whole HTML source is known and parsed by the browser), do some code." The reason your example is not working is because you're trying to execute some code on a selection ($('a')) BEFORE the browser knows about all of the <a> tags on the page. Putting your code inside $(document).ready() will make sure your code isn't actually executed until the whole document is parsed. In your example, there aren't any <a> tags known to the browser when your code executes...

Alternatively, you can just put your entire <script> tag *after* the anchor tag occurs in the source. This ensures that the browser is "aware" that the anchor tag exists before it attaches your click() handler to the link.

Either way, the browser has to know about (have parsed) the anchor tag before you can work with it via jQuery.

No 'this' there

Just wanted to point out that one of the topics in the section header "3 Callbacks, Functions, and 'this'" is actually not in the article (no discussion of 'this'). --Bburwick 15:35, 21 August 2007 (PDT)