官术网_书友最值得收藏!

Time for action – adding a new paragraph

Perform the following steps to add a new paragraph to our page:

  1. We need to tell jQuery what to do when the document is ready. Since we want something to happen, we'll pass in a function like this:
    $(document).ready(function(){
      // Our code will go here
    });

    We'll write what's going to happen inside this function.

    What about the line that starts with //? That's one way of writing a comment in JavaScript. The // sign tells JavaScript to ignore everything else on that line because it's a comment. Adding comments to your JavaScript is a great way to help yourself keep track of what's happening on what line. It's also great for helping along other developers who might need to work on your code. It can even be great for helping yourself if you haven't looked at your own code in a few months.

  2. Next, we'll add what we want the function to do as soon as the document is ready:
    $(document).ready(function(){
      $('body').append('<p>This paragraph was added with jQuery!</p>');
    });

What just happened?

Our new function is using the jQuery function again, as follows:

$('body')

Remember I said that jQuery uses CSS selectors to find stuff? This is how we use those CSS selectors. In this case, we want the <body> tag, so we'll going to pass body to the jQuery function. This returns the <body> tag wrapped in a jQuery object. Handily, the jQuery object has an append method that lets us add something new to the page, as follows:

$('body').append();

All we have to do is call the append method and pass in the paragraph we want to add to the page. In quotes, pass a line of HTML:

$('body').append('<p>This paragraph was added with jQuery!</p>');

That's it! Now, when you load the page in a browser, you'll see the heading followed by two paragraphs—jQuery will add the second paragraph as soon as the document is loaded in the browser. The following screenshot shows the page loaded in the browser:

Have a go hero – adding more content

Try adding the following bit of HTML to the bottom of the document with jQuery:

<div><p>This was added with jQuery too!</p></div>

Style it with CSS so that it stands out.

主站蜘蛛池模板: 普陀区| 沅陵县| 浦县| 长武县| 新乡县| 同德县| 法库县| 惠来县| 收藏| 滦平县| 高尔夫| 志丹县| 霍城县| 溧阳市| 云浮市| 融水| 闵行区| 漳州市| 乾安县| 清水河县| 格尔木市| 上犹县| 扶绥县| 禹州市| 泸溪县| 崇左市| 辰溪县| 大关县| 兴义市| 屏山县| 合阳县| 南乐县| 读书| 沙湾县| 台中县| 南召县| 新营市| 黎城县| 明溪县| 保靖县| 广宁县|