TOC

The community is working on translating this tutorial into Chinese, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Introduction:

Hello, world!

基本上,每一个编程教程都会从“Hello,world!"这个列子开始,我们这个教程也不例外。在上一章中,我们学习了如何在页面中使用jQuery,所以现在我们可以开始使用它的所有功能。但是在你开始写代码之前,你需要更多地了解jQuery的运作。为了确保所有一切都能运作,也为了让你能看看jQuery有多简单,我们将从一个简单的小列子开始。

<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>

Okay, so we have a div tag with the id of "divTest1". In the JavaScript code we use the $ shortcut to access jQuery, then we select all elements with an id of "divTest1" (there is just one though) and set its text to "Hello, world!". You may not know enough about jQuery to understand why and how this works, but as you progress through this tutorial, all of the elements will be explained in detail.

Even such a simple task as this one would actually require quite a few extra keystrokes if you had to do it in plain JavaScript, with no help from jQuery:

<div id="divTest2"></div>
<script type="text/javascript">
document.getElementById("divTest2").innerHTML = "Hello, world!";
</script>

And it would be even longer if our HTML element didn't have an ID, but for instance just a class.

Normally though, you should wait for the document to enter the READY state before you start manipulating its content. The above examples will work in most browsers and likely even work when you do more advanced stuff, but certain tasks may fail if you try to do them before the document is loaded and ready. Fortunately, jQuery makes this very easy as well, as we will see in the next chapter. After that, we will start looking into one of the most important aspects of jQuery, which has already been used in the above example: Selectors.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!