【文章內(nèi)容簡(jiǎn)介】
h we‘ll put the quote once we‘ve received it from the server. We‘ll use jQuery to select this div and load the quote into it, and we‘ll reference the div by its id. If we wanted to, we could use jQuery to load the quote into multiple elements, with the help of a class, but an id is all we need for now. Let‘s make this the content of our body element: input type=submit id=generate value=Generate! div id=quote/div We can put the quote itself inside the div. Normally, we‘d have a lengthy onSubmit event for the button (the input with the id 39。generate39。). Sometimes, we‘d have an onSubmit event handler that called a JavaScript function. But with jQuery, we don‘t even need to touch the HTML — we can separate behavior (the event handler) from the structure (the page HTML) with ease. Clientside Code (jQuery) It‘s time to bring our back end together with our front end using jQuery. I mentioned earlier that we can select elements from the DOM with jQuery. First, we 4 have to select the button and assign an onClick event handler to it. Within the code for this event, we can select the div and load the content of our script into it. Here‘s the syntax for the click event handler: $(element expression).click(function(){ // Code goes here })。 As you probably already know, if we were to select this element in CSS, the would identify that we were making our selection using the element‘s id attribute. You can use exactly the same syntax with jQuery. Therefore, to select the button with the id 39。generate39。 (which we gave it above), we can use the element expression generate. Also, be aware that this syntax defines our event handler as an anonymous function within the event itself. Mark Wubben‘s JavaScript Terminology page offers a great explanation of anonymous functions, if you‘d like to know more. We‘re going to use one of jQuery‘s higher level Ajax functions, load(). Let‘s assume that our generator script is saved as . Let‘s integrate it with our client side with the help of the load() function: $(generate).click(function(){ $(quote).load()。 })。 That‘s it: three lines of code, and we have fully functioning Ajax random quote generator! Well, almost. The problem with JavaScript is that code that‘s not within a function is executed as soon as the browser reaches it during rendering — not once the page has finished rendering. As such, this code will try to attach to an element that has not yet loaded. Normally, we‘d use to deal with this issue. However, the limitation with that approach is that is called once everything has finished loading — images and all. We‘re not interested in waiting for those images — it‘s just the DOM that we want access to. Fortunately, jQuery has $(document).ready(), which, as its name suggests, is executed when the DOM is ready to be manipulated. The Complete Code Here‘s the plete code, including the $(document).ready wrapper and some