Tải bản đầy đủ (.pdf) (9 trang)

Lập trình .net 4.0 và visual studio 2010 part 43 doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (396.47 KB, 9 trang )

CHAPTER 12  JQUERY

280
Adding Functions
A common problem many designers and developers encounter is the separation of design from code.
Many developers (in fact, I got you to do this in the very first example) if asked to call a JavaScript
function when a button is clicked will write something such as this:


<input id="cmdTest" type="button" value="Hello jQuery"
onclick="javascript:hellojQuery();" />

However this is not the best way because it is very vulnerable to polo neck, snowboarding designer
corruption and isn’t standards compliant.
jQuery offers a neat solution with the .bind() method. The following code binds the hellojQuery()
function to the click of the cmdTest button:

$("#cmdTest").bind('click', hellojQuery());''
Animation/Effects
Many people become aware of jQuery through seeing one of its many impressive graphical effects.
Let’s check out the fadeOut effect using our original example.
1. Go back to default.htm and change the helloJQuery() function to contain the following:
$("#div1").fadeOut();
2. Press F5 to run your application,
3. Click the Hello jQuery button,
4. The div should then fade out of view.
Effect Overloads
Most of the effects in jQuery are overloaded, allowing fine-grained control (see Table 12-6).
Table 12-6. Different overloads of fadeOut method
Exa mple
Me ani ng


$("#div1").fadeOut(); Basic effect with default options
$("#div1").fadeOut(10000); Effect time specified in milliseconds
$("#div1").fadeOut('slow'); Specifies the time the effect will take to run: slow,
normal, or fast

CHAPTER 12  JQUERY

281
You can also specify a callback function to be executed when the effect has completed:

function hellojQuery()
{
$("#div1").fadeOut('slow',funtionToCall);
}

Function functionToCall()
{

}
Core Library Effects
Table 12-7 lists jQueries core effects.
Table 12-7. Core libary effects
Exa mple
Me ani ng
$("#div1").hide(); Hides element.
$("#div1").show(); Shows element.
$("#div1").fadeOut(); Fades out element.
$("#div1").fadeIn(); Fades in element.
$("#div1").toggle(); Toggles display of element. If it is hidden, it will become visible. If
it is visible, it will be hidden.

$("#div1").slideDown(); Animates element to become visible like a vertical blind sliding
down.
$("#div1").slideUp(); Animates element to become hidden like a vertical blind sliding
up.
$("#div1").animate({ Powerful function that animates an element to specified CSS
property values over time span in milliseconds specified.
width: "100%",
fontSize: "100px"
}, 1500 );
$("#div1").stop();
Stops any animation or effects in progress.
CHAPTER 12  JQUERY

282
Additional Effects
In addition to the previous effects, a number of additional effects can be downloaded: fold, pulsate, puff,
bounce, and explode (my personal favorite). For more details on these effects please go to http://docs.
jquery.com/UI/Effects.
Glimmer
If you don’t want to hand-code your jQuery effects, you can use a great tool called Glimmer produced by
Microsoft that offers a wizard-based approach (see Figure 12-4). Refer to
glimmer.

Figure 12-4. Glimmer allows you to easily construct jQuery effects
Glimmer allows the construction of simple effects such as rotating images, drop-down menus, and
animation.
jQuery Tools
jQueryPad ( ( and can be very useful tools
for prototyping and playing with jQuery.


CHAPTER 12  JQUERY

283
Chaining Events
The real power of jQuery comes from its capability to chain functions together. Imagine that we wanted
to fade our div in and out a number of times. This procedure can be easily accomplished with the
following code:

$("#div1").fadeOut().fadeIn().fadeOut().fadeIn().fadeOut();
Customizing jQuery
You can add your own functions to the jQuery library. For example, to create a simple function that will
pop up an alert box, you can do so with the following code:

//don't use $ alias in case user overrides it
jQuery.fn.say = function (message) {
alert("jQuery says " + message);

return this;
}

You can then call the new function with the following code:

$.fn.say("hello").say("good bye");

And there is, of course, no reason why you couldn’t write a new effects function and use it as part of
a chain of effects.
For more information, please refer to
AJAX Methods
It is very common for performance optimization to need to retrieve data or code from an external source
after a page is loaded. jQuery makes this very easy.

Load and Run JavaScript File
The following code loads an external JavaScript file called test.js and then executes it:

$.ajax({
type: "GET",
url: "test.js",
dataType: "script"
});

The test.js file consists of just the following line:

alert('hello');
CHAPTER 12  JQUERY

284
Submitting Data
You often need to submit data to another web page. This can easily be done with the following code:

$.ajax({
type: "POST",
url: "myForm.aspx",
data: "firstname=Alex&lastname=Mackey",
success:
function() {
alert("form submitted");
}
});

You will use this functionality in the ASP.NET MVC example (see Chapter 13) to submit your form
data:


//Submit client side
$.ajax({
type:
"POST",
dataType: "json",
url: "Edit",
data: { Description: InputDescription, Length: InputLength,
DateShowing: InputDateShowing },
success: function(result) {
alert(result.Message + " adding film at " + result.DateShowing);
},
error: function(error) {
alert('error ');
}
});
Getting the Latest Version of a Page
We can retrieve the contents of a page in the same domain as the calling page with a few lines of code.
This could be useful in AJAX scenarios in which you want to load content behind the scenes:

$.ajax({
url: "default2.aspx",
cache: false,
success: function(returnHtml) {
$("#div1").append(returnHtml);
}
});
CHAPTER 12  JQUERY

285

Retrieving a JSON Object
JSON is a compact format for representing data. jQuery contains support for working with JSON objects.
We will first create a page called default2.aspx that will return a JSON-formatted string (you will soon
look at a better way of doing this).
1. Right-click your solution and add a new page called default2.aspx and select the place code in
a seperate file option.
2. Remove all the code on default2.aspx except for the page declaration.
3. Add the following code to default2.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Response.Buffer = true;
Response.Clear();
Response.ContentType = "application/json";
Response.Write("{firstName: \"Alex\",lastName: \"Mackey\"}");
}
4. Open default.htm and alter the helloJQuery() function to the following (note that we pass a
URL to which we send the query and then a function to be called when the query is completed):
$.getJSON("default2.aspx",
function (data) {
alert(data.firstName);
}
);
5. Press F5 to run the project.
6. Click the Hello jQuery button.
You should see an alert box displaying “Alex” (the firstName property from the JSON object).
A Better Way
Visual Studio 2008 (and later) offers a better way:
1. Create a new page called default3.aspx and then open default3.aspx.cs.
2. Add the following using statement:
using System.Web.Services;

3. Add the following class to represent our returned object:
public class Person
{
public string firstName {get; set;}
public string lastName { get; set; }
}


CHAPTER 12  JQUERY

286
4. Now add a new method to your page marked with the [WebMethod] attribute to expose it to the
client script:
[WebMethod]
public static Person GetFirstname()
{
Person p = new Person();
p.firstName = "Alex";
p.lastName = "Mackey";

return p;
}
5. Now amend the existing jQuery code to the following:
$.ajax({
type: "POST",
url: "Default3.aspx/GetFirstname",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (input) {

alert(input.d.firstName);
}
});

Much easierand safer. Note that we had to access the d property in order to access the firstName
property. This is to prevent the execution of the returned string as a script. For more information, please
refer to:
Utility Methods
Browser detection is notoriouslly unreliable, but jQuery provides a number of methods to assist you with
detecting the capabilities of your visitors’ browsers. For example, the following code will return true or
false depending on whether the browser supports the box rendering model:

alert($.support.boxModel);

For the full list of functionality you can query, please see
jQuery.support.
jQuery Additions
In addition to the core jQuery functionality, a number of additional jQuery libraries and add-ons exist
that you might find useful. Note some of these are not produced by the core jQuery team but are
excellent nevertheless:
• Drag and drop elements (
• Sorting (
• Selecting (
CHAPTER 12  JQUERY

287
• Resizing (
• jqgrid (
jQuery also provides a number of UI elements (called widgets) that you might want to utilize:
• Accordian

• Data picker
• Dialog
• Progress bar
• Slider
• Tabs
For more information, please refer to
Summary
It is fantastic to see Microsoft not reinventing the wheel and choosing to integrate and provide support
for jQuery. jQuery is a lightweight framework, and you would be crazy not to use it in your own projects.
Further Reading


• />cdn.aspx


For a more in-depth read on jQuery functions, I don’t think you can do much better than jQuery in
Action by Bear Bibeault and Yehuda Katz, published by Manning.



×