jQuery para programadores Javascript

Jquery desde Enero del 2006,

Jquery es una pieza de ingeniería que encapsula un rango de funciones comunes (necesarias) y provee una API para desarrollar plugins para cualquier funcionalidad que no esté incluida por defecto.
Es una abstracción con una selección de elementos DOM.

¿Qué es jQuery?

Created by John Resig in early 2006, jQuery is a great library for anyone who works with JavaScript code. Creado por John Resig a principios de 2006, jQuery es una gran biblioteca para todo aquel que trabaja con código JavaScript. Whether you’re new to the JavaScript language and want a library to address some of the complexities of Document Object Model (DOM) scripting and Ajax or you’re an advanced JavaScript guru and tired of the boring repetition involved with DOM scripting and Ajax, jQuery will suit you well. Si eres nuevo en el lenguaje JavaScript y quieren una biblioteca para hacer frente a algunas de las complejidades de Document Object Model (DOM) y Ajax de secuencias de comandos o es usted un avanzado JavaScript guru y cansado de la aburrida repetición involucrados con scripting DOM y Ajax, jQuery se ajusten a lo mejor.

Algunas sencillas simplificaciones

He aquí un simple ejemplo de los efectos jQuery puede tener en su código. Para hacer algo realmente simple y común, como adjuntar un evento Click para cada eslabón de una zona de una página, usted uso sencillo código JavaScript y DOM de secuencias de comandos, como se muestra en el Listado 1.
Listing 1. DOM scripting without jQuery DOM scripting sin jQuery

 var external_links = document.getElementById('external_links'); external_links var = document.getElementById ( 'external_links');
 var links = external_links.getElementsByTagName('a'); var enlaces external_links.getElementsByTagName = ( 'uno');
 for (var i=0;i < links.length;i++) { para (var i = 0; i <links.length; i + +) (
     var link = links.item(i); var link = links.item (i);
     link.onclick = function() { link.onclick = function () (
         return confirm('You are going to visit: ' + this.href); return confirm ( "Usted va a visitar: '+ this.href);
     }; );
 } )

Listing 2 shows the same functionality achieved using jQuery. Listado 2 muestra la misma funcionalidad conseguirse utilizando jQuery.
Listing 2. DOM scripting with jQuery DOM scripting con jQuery

 $('#external_links a').click(function() { $ ( '# external_links uno'). Haz click (function () (
     return confirm('You are going to visit: ' + this.href); return confirm ( "Usted va a visitar: '+ this.href);
 }); ));

Increíble, ¿no? Con jQuery, obtiene el derecho a punto, y expresar sólo lo que quiere el código para hacerlo sin todos los problemas. No hay necesidad de bucle sobre los elementos, click() clic en click() la función se encarga de ello. Asimismo, no hay necesidad de hacer múltiples llamadas scripting DOM: Todo lo que usted necesita es una cadena corta para definir los elementos a trabajar.

Puede ser un poco difícil de entender cómo este código es incluso el trabajo. En primer lugar, se tiene  a la función más poderosa $() de jQuery. Mayormente, se utiliza esta función para seleccionar elementos del documento. En este ejemplo, a la función se le pasa una cadena que contiene algunas hojas de estilo en cascada (CSS) de sintaxis y jQuery considera los elementos de la forma más eficiente posible.

Si conoces los fundamentos de la CSS, selectores, ésta sintaxis debe ser familiar. En el Listado #external_links # #external_links busca el elemento con un id de external_links. Un espacio seguido de a cuenta jQuery para buscar todos los <a> elementos en el interior de la external_links elemento. Eso es un bocado que decir en Inglés – e incluso en secuencias de comandos DOM – pero en la CSS, no podía ser más simple.

The $() function returns a jQuery object containing all the elements that match the CSS selector. $() La funci función $() devuelve un objeto jQuery que contiene todos los elementos que coinciden con el selector CSS.

jQuery object is something like an array but comes with a ton of special jQuery functions. JQuery

Un objeto JQuery es algo así como un arreglo (serie), pero permite utilizar más  funciones especiales. For example, you can assign a click handler function to each element in the jQuery object by calling the click function. Por ejemplo, puede asignar un manejador haga clic en función de cada uno de los elementos en el objeto jQuery llamando a la click la función.

You can also pass an element or an array of elements to the $() function, and it will wrap a jQuery object around the elements. Usted también puede pasar un elemento o una serie de elementos $() los $ $() función, y se envuelva un objeto jQuery en torno a los elementos. You might want to use this functionality to employ jQuery functions on things like the window object. Es posible que desee utilizar esta funcionalidad para emplear jQuery funciones en cosas como la window objeto. For example, you typically assign the function to the load event like this: Por ejemplo, que suelen asignar la función de la carga evento como este:

 window.onload = function() { window.onload = function () (
     // do this stuff when the page is done loading / / Hacer estas cosas cuando la página se realiza la carga
 }; );

Using jQuery, you write the same code like this: El uso de jQuery, que escribe el mismo código como este:

 $(window).load(function() { $ (ventana). carga (function () (
     // run this when the whole page has been downloaded / / Ejecutar este momento toda la página se ha descargado
 }); ));

As you probably already know, waiting for the window to load is painfully slow, because the whole page must finish loading, including all the images on the page. Sometimes, you want the images to finish loading first, but most of the time, you just need the Hypertext Markup Language (HTML) to be there. Como probablemente ya saben, a la espera de la ventana de carga es dolorosamente lento, porque toda la página debe terminar la carga, incluidas todas las imágenes de la página. Ocasiones, que desea las imágenes para terminar de cargar en primer lugar, pero la mayor parte del tiempo, usted Sólo necesitamos el Lenguaje de marcado de hipertexto (HTML) para estar allí. jQuery solves this problem by creating a special ready event on the document, used like this: jQuery resuelve este problema mediante la creación de un especial ready sobre el documento, se usa así:

 $(document).ready(function() { $ (document). dispuestas (function () (
     // do this stuff when the HTML is all ready / / Hacer estas cosas cuando el HTML es todo listo
 }); ));

This code creates a jQuery object around the document element, then sets up a function to call the instance when the HTML DOM document is ready. Este código crea un objeto jQuery todo el document y, a continuación, se establece una función para llamar a la instancia cuando el HTML DOM documento está listo. You can call this function as many times as necessary. Usted puede llamar a esta función tantas veces como sea necesario. And, in true jQuery style, a shortcut calls this function. Y, en cierto estilo jQuery, un acceso directo llama a esta función. Simply pass a function to the $() function: Basta con pasar una función $() los $ $() función:

 $(function() { $ (function () (
     // run this when the HTML is done downloading / / Ejecutar este cuando el HTML se realiza la descarga
 }); ));

So far, I’ve shown you three different ways to use the $() function. Hasta el momento, he demostrado que tres formas diferentes de utilizar $() $ $() función. With a fourth way, you can create an element using a string. Con una cuarta manera, puede crear un elemento mediante una cadena. The result is a jQuery object containing that element. Listing 3 shows an example that adds a paragraph to the page. El resultado es un objeto jQuery que contengan este elemento. Listado 3 muestra un ejemplo que añade un párrafo a la página.
Listing 3. Listado 3. Creating and appending a simple paragraph Crear y añadir un párrafo simple

 $('<p></p>') $ ( '<p> </ p>')
     .html('Hey World!') . html ( 'Hola Mundo! ")
     .css('background', 'yellow') . css ( 'antecedentes',' amarillo ')
     .appendTo("body"); . appendTo ( "cuerpo");

As you might have noticed from the previous example, another powerful feature of jQuery is method chaining. Every time you call a method on a jQuery object, the method returns the same jQuery object. Como usted habrá notado desde el ejemplo anterior, otra característica de jQuery método es encadenar. Cada vez que usted llame a un método sobre un objeto jQuery, el método devuelve el mismo objeto jQuery. This means that if you need to call multiple methods on a jQuery object, you can do it without re-typing the selector: Esto significa que si usted necesita llamar a varios métodos en un objeto jQuery, puede hacerlo sin necesidad de volver a escribir el selector:

 $('#message').css('background', 'yellow').html('Hello!').show(); $ ( '# mensaje "). css (' antecedentes', 'amarillo'). html ( 'Hello!"). show ();

Ajax made simple Ajax hecho simple

Ajax couldn’t be any easier than it is with jQuery. Ajax no podría ser más fácil de lo que es con jQuery. jQuery has a handful of functions that make the easy stuff really easy and the complex stuff as simple as possible. jQuery tiene un puñado de funciones que hacen fácil la cosa muy fácil y las complejas cosas lo más simple posible.

A common use of Ajax is to load a chunk of HTML into an area of the page. Un uso común de Ajax es para cargar un fragmento de HTML en una zona de la página. To do that, simply select the element you need and use the load() function. Para ello, simplemente seleccione el elemento que necesita y el uso load() la carga load() función. Here’s an example that updates some statistics: He aquí un ejemplo de que las actualizaciones de algunas estadísticas:

 $('#stats').load('stats.html'); $ ( '# estadísticas »). carga (' stats.html ');

Often, you simply need to pass some parameters to a page on the server. A menudo, sólo tendrá que pasar algunos parámetros a una página en el servidor. As you’d expect, this is incredibly simple in jQuery, too. Como usted esperaba, esto es increíblemente simple en jQuery, también. You can use choose between $.post() and $.get() , depending on which method you need. Usted puede elegir entre utilizar $.post() $.get() en función de que el método que usted necesita. You can pass an optional data object and callback function if you need them. Listing 4 shows a simple example that sends data and uses a callback. Puede pasar un objeto de datos opcional y la función de llamada en caso de que los necesite. Listado 4 muestra un ejemplo sencillo que envía los datos y utiliza una llamada.
Listing 4. Listado 4. Sending data to a page with Ajax Envío de datos a una página con Ajax

 $.post('save.cgi', { $. posteriores ( 'save.cgi', (
     text: 'my string', texto: "mi cadena",
     number: 23 Número: 23
 }, function() { ), Function () (
     alert('Your data has been saved.'); alert ( 'Su información se ha guardado. ");
 }); ));

If you really want to do some complex Ajax scripting, you need the $.ajax() function. Si realmente quiere hacer algunas secuencias de comandos complejas Ajax, que necesita $.ajax() función. You can specify xml , html , script , or json , and jQuery automatically prepares the result for your callback function so that you can use it right away. Puede especificar xml script o json y jQuery prepara automáticamente el resultado de su función callback para que pueda utilizarlo de inmediato. You can also specify beforeSend , error , success , or complete callbacks to give the user more feedback about the Ajax experience. También puede especificar error success el éxito, complete completar llamadas a dar al usuario más información acerca de la experiencia Ajax. In addition, other parameters are available with which you can set the timeout of an Ajax request or the «Last Modified» state of a page. Listing 5 shows an example that retrieves an XML document using some of the parameters that I mentioned. Además, otros parámetros están disponibles con los que se puede establecer el tiempo de una solicitud Ajax o la «Última modificación» estado de una página. Listado 5 muestra un ejemplo que recupera un documento XML utilizando algunos de los parámetros que he mencionado.
Listing 5. Listado 5. Complex Ajax made simple with $.ajax() Complejo Ajax hecho simple de dólares. Ajax ()

 $.ajax({ $. ajax ((
     url: 'document.xml', url: 'document.xml »,
     type: 'GET', Tipo: 'GET',
     dataType: 'xml', DataType: "xml",
     timeout: 1000, tiempo: 1000,
     error: function(){ error: function () (
         alert('Error loading XML document'); alert ( "Error al cargar el documento XML ');
     }, ),
     success: function(xml){ éxito: function (xml) (
         // do something with xml / / Hacer algo con xml
     } )
 }); ));

When you get the XML back in the success callback, you can use jQuery to look through the XML the same way you do with HTML. Al obtener el XML en el éxito de devolución de llamada, usted puede usar jQuery mirar a través del XML de la misma manera que ver con HTML. This makes it easy to work with an XML document and integrate the contents and data into your Web site. Listing 6 shows an expansion on the success function that adds a list item to the Web page for each <item> element in the XML. Esto hace que sea fácil trabajar con un documento XML e integrar el contenido y los datos en su sitio Web. Listado de 6 muestra una expansión en el success la función que añade un elemento de la lista a la página Web para cada <item> elemento en el XML.
Listing 6. Listado 6. Working with XML using jQuery Trabajar con XML utilizando jQuery

 success: function(xml){ éxito: function (xml) (
     $(xml).find('item').each(function(){ $ (xml). hallar ( 'tema'). cada uno (function () (
         var item_text = $(this).text(); item_text var = $ (este). texto (); 

         $('<li></li>') $ ( '<li> </ li>')
             .html(item_text) . html (item_text)
             .appendTo('ol'); . appendTo ( 'OC');
     }); ));
 } )

Animate your HTML Animar el código HTML

You can use jQuery to take care of basic animations and effects. Puede utilizar jQuery para cuidar de base de animaciones y efectos. At the heart of the animation code is the animate() function, which changes any numeric CSS style value over time. En el corazón de la animación es el código de animate() función, que los cambios numéricos de cualquier estilo CSS valor en el tiempo. For example, you can animate height, width, opacity, or position. Por ejemplo, puede animar altura, anchura, opacidad, o de posición. You can also specify the speed of the animation, either in milliseconds or in one of the predefined speeds: slow, normal, or fast. También puede especificar la velocidad de la animación, ya sea en milisegundos o en uno de los predefinidos velocidades: lento, normal o rápido.

Here’s an example that animates the height and width of an element at the same time. Notice that there is no start value — only the end value. He aquí un ejemplo que anima a la altura y la anchura de un elemento al mismo tiempo. Observe que no hay valor de inicio – sólo el valor final. The start values are taken from the current size of the element. El comienzo valores se toman de la actual tamaño del elemento. I’ve also attached a callback function. También he adjuntado una función de llamada.

 $('#grow').animate({ height: 500, width: 500 }, "slow", function(){ $ ( '# crecer »). animan ((altura: 500, ancho: 500)," lento ", function () (
     alert('The element is done growing!'); alert ( 'El elemento se hace cada vez más!');
 }); ));

jQuery makes the more common animations easier with built-in functions. jQuery hace que el más común animaciones más fácil con funciones incorporadas. You can use show() and hide() elements, either instantly or at a specified speed. Puede utilizar show() y hide() elementos, ya sea al instante o en una determinada velocidad. You can also make elements appear and disappear by using fadeIn() and fadeOut() or slideDown() and slideUp() , depending on what kind of effect you’re looking for. Usted también puede hacer elementos aparecen y desaparecen mediante el uso de fadeIn() fadeOut() slideDown() slideUp() dependiendo de qué tipo de efecto que buscas. Here’s a simple example that slides down a navigation: He aquí un ejemplo sencillo que se desliza hacia abajo una de navegación:

 $('#nav').slideDown('slow'); $ ( '# nav'). slideDown ( 'lento');

DOM scripting and event handling DOM scripting y de manejo de evento

jQuery is, perhaps, best at simplifying DOM scripting and event handling. jQuery es, quizás, a simplificar las mejores DOM scripting y de manejo de evento. Traversing and manipulating the DOM is easy, and attaching, removing, and calling events is completely natural and much less error prone than doing it by hand. Atravesar la manipulación y el DOM es fácil, y adjuntando, la eliminación, y llamando a los eventos es completamente natural y mucho menos propenso a errores que hacerlo a mano.

In essence, jQuery makes it easier to do things that are common with DOM scripting. You can create elements and use the append() function to link them to other elements, use clone() to duplicate elements, set the contents with html() , delete the contents with the empty() function, delete the elements altogether with the remove() function, and even use the wrap() function to wrap the elements with another element. En esencia, jQuery hace que sea más fácil de hacer las cosas que son comunes con scripting DOM. Puede crear los elementos y el uso de la append() la función de vincular a otros elementos, el uso clone() duplicar los elementos, conjunto con el contenido html() , Borrar el contenido con el empty() función, eliminar los elementos que en conjunto con la remove() función, e incluso el uso wrap() envolver los elementos con otro elemento.

Several functions are available for changing the contents of the jQuery object itself by traversing the DOM. Varias de las funciones están disponibles para modificar el contenido del objeto en sí jQuery por atravesar el DOM. You can get all the siblings() , parents() , or children() of an element. Usted puede obtener todos los siblings() los padres parents() children() los niños children() de un elemento. You can also select the next() or prev() sibling elements. También puede seleccionar el next() prev() hermano elementos. Perhaps most powerful is the find() function, which allows you to use a jQuery selector to search through the descendants of elements in your jQuery object. Tal vez lo más poderoso es el find() función, que le permite usar un selector de jQuery para buscar a través de los descendientes de los elementos en su objeto jQuery.

These functions become more powerful when used with the end() function. Estas funciones cada vez más potente cuando se utiliza end() el fin end() función. This function is like an undo function, going back to the jQuery object you had before you called find() or parents() or one of the other traversing functions. Esta función es como una función «deshacer», que se remonta a la jQuery objeto que había llamado antes de find() parents() una de las demás funciones que atraviesan.

When used together with method chaining, these functions allow complex operations to look simple. Listing 7 shows an example in which you find a login form and manipulate several elements around it. Cuando se utiliza junto con el método de encadenamiento, estas funciones permiten operaciones complejas para buscar simple. Listado 7 muestra un ejemplo en que se encuentra un formulario de acceso y manipular varios elementos a su alrededor.
Listing 7. Listado 7. Traversing and manipulating the DOM with ease Atravesar la manipulación y la DOM con facilidad

 $('form#login') $ ( "# forma login ')
     // hide all the labels inside the form with the 'optional' class / / Ocultar todas las etiquetas en el interior de la forma con la 'opcional' class
     .find('label.optional').hide().end() . hallar ( 'label.optional'). ocultar (). final () 

     // add a red border to any password fields in the form / / Añadir un borde rojo a cualquier contraseña en los campos de forma
     .find('input:password').css('border', '1px solid red').end() . hallar ( 'entrada: password'). css ( 'frontera','1 px rojo '). final () 

     // add a submit handler to the form / / Añadir un manejador de presentar a la forma
     .submit(function(){ . presentará (function () (
         return confirm('Are you sure you want to submit?'); return confirm ( '¿Está seguro de que desea enviar? ");
     }); ));

Believe it or not, this example is just a single, chained, line of code spread out with whitespace. Lo creas o no, este ejemplo es un solo, encadenado, línea de código extendido con blanco. First, I selected the login form. En primer lugar, he seleccionado el formulario de acceso. Then, I found the optional labels inside it, hid them, and called end() to go back to the form. Luego, he encontrado la opción de etiquetas dentro de él, ocultó, y pidió end() para volver a la forma. I found the password field, made the border red, and again called end() to go back to the form. He encontrado el campo de la contraseña, hizo de la frontera de color rojo, y volvió a pedir end() para volver a la forma. Finally, I added a submit event handler to the form. Por último, he añadido un evento presentará a la forma. What’s especially interesting about this (besides its obvious brevity) is that jQuery completely optimizes all the query operations, making sure that you don’t have to find an element twice when everything is nicely chained together. ¿Cuál es especialmente interesante acerca de este (además de su evidente brevedad) es completamente jQuery que optimiza todas las operaciones de consulta, asegurándose de que usted no tiene que encontrar un elemento dos veces cuando todo está muy bien encadenados juntos.

Handling common events is as simple as calling a function like click() , submit() , or mouseover() and passing it an event handler function. Manejo de eventos común es tan simple como llamar a una click() como hacer clic click() submit() o mouseover() pasándole una función de eventos. Additionally, you have the option of assigning a custom event handler using bind('eventname', function(){}) . You can remove certain events using unbind('eventname') or all events with unbind() . Además, tiene la opción de asignar un evento personalizado utilizando bind('eventname', function(){}) Puede eliminar ciertos eventos usando unbind('eventname') todos los eventos con unbind() For a complete list of ways to use these and other functions, check out the jQuery application program interface (API) documentation in the Resources . Para obtener una lista completa de las maneras de utilizar estas y otras funciones, consulte el jQuery interfaz de programación de aplicaciones (API) la documentación de los Recursos.


Unleash the power of jQuery selectors Libere el poder de los selectores de jQuery

Often, you select elements by ID, such as #myid , or by class name, such as div.myclass . A menudo, se selecciona por elementos de identificación, como por ejemplo #myid o por el nombre de clase, como div.myclass However, jQuery has a rather complex and complete selector syntax that allows you to select nearly any combination of elements in a single selector. Sin embargo, jQuery tiene una compleja y completa selección de la sintaxis que le permite seleccionar casi cualquier combinación de elementos en un solo selector.

jQuery’s selector syntax is based heavily on CSS3 and XPath. jQuery selector de la sintaxis se basa en gran medida en CSS3 y XPath. The more you know about CSS3 and XPath syntax, the better you’ll be at using jQuery. Cuanto más sepa sobre CSS3 XPath y sintaxis, mejor usted será en el uso de jQuery. For a complete list of jQuery selectors, including CSS and XPath, check out the links in Resources . Para obtener una lista completa de selectores de jQuery, incluyendo CSS y XPath, echa un vistazo a los enlaces de los recursos.

CSS3 contains some syntax that not every browser supports, so you don’t see it often. CSS3 contiene algunas sintaxis que no apoya todos los navegadores, por lo que no veo a menudo. However, you can still use CSS3 in jQuery to select elements, because jQuery has its own, custom selector engine. Sin embargo, aún puede utilizar en CSS3 jQuery para seleccionar los elementos, porque jQuery tiene su propio, la costumbre de selección de motor. For example, to add a dash inside every empty column of a table, use the :empty pseudo-selector: Por ejemplo, para añadir un guión vacío dentro de cada columna de una tabla, utilice la :empty pseudo-selector:

 $('td:empty').html('-'); $ ( 'TD: vacío'). ('-'); html

What about finding every element that doesn’t have a certain class? ¿Qué hay de encontrar cada elemento que no tenga una cierta clase? CSS3 has a syntax for that, too, using the :not pseudo-selector. Here’s how you can hide every input that doesn’t have a class of required : CSS3 tiene una sintaxis para que, también, utilizando :not pseudo-selector. A continuación le indicamos cómo puede esconder cada entrada que no tiene una clase required exigencias:

 $('input:not(.required)').hide(); $ ( "de entrada: no (. requerido)»). hide ();

You can also join multiple selectors into one using commas, just as in CSS. Usted también puede unirse a varios selectores en una utilización de comas, al igual que en CSS. Here’s a simple example that hides every type of list on the page at the same time: He aquí un ejemplo simple que esconde todo tipo de lista en la página al mismo tiempo:

 $('ul, ol, dl').hide(); $ ( 'ul, ol, dl'). hide ();

XPath is a powerful syntax for finding elements in a document. XPath es una potente sintaxis para la búsqueda de elementos en un documento. It’s a bit different than CSS and lets you do a few things you can’t do with CSS. Es un poco diferente a la CSS y le permite hacer un par de cosas que no puedes hacer con CSS. To add a border to the parent element of every check box, you can use XPath’s /.. syntax: Para añadir un borde a la matriz elemento de cada casilla, puede usar la XPath /.. sintaxis:

 $("input:checkbox/..").css('border', '1px solid #777'); $ ( "input: casilla /.."). css ( 'frontera','1 px sólido # 777 ');

jQuery adds extra selectors that aren’t available in CSS or XPath, as well. jQuery añade extra selectores que no están disponibles en CSS o XPath, también. For example, to make a table more readable, you would typically attach a different class name to every odd or even row of the table — otherwise known as striping the table. Por ejemplo, para hacer un cuadro más legible, se suele adjuntar una clase diferente nombre a cada par o impar de la tabla – también conocido como bandas de la mesa. Doing this with jQuery is a cinch, thanks to the :odd pseudo-selector. Hacer esto con jQuery es un pan, gracias a :odd seudo-selector. This example changes the background of every odd row in tables with a striped class: En este ejemplo se cambia el fondo de cada fila extraño en las tablas con una striped de clase:

 $('table.striped > tr:odd').css('background', '#999999'); $ ( 'table.striped> tr: impares "). css (' antecedentes', '# 999999');

You can see how the power of jQuery selectors can simplify your code. Usted puede ver cómo el poder de los selectores de jQuery puede simplificar el código. Whatever selection of elements you want to affect, no matter how specific or obscure, you can probably find a way to define them using a single jQuery selector. Sea cual sea la selección de los elementos que desea afectar, no importa cuán específica u oscuro, puede probablemente encontrar una manera de definir mediante un selector único jQuery.


Extend jQuery with plug-ins Amplíe jQuery con plug-ins

Unlike with most software, writing plug-ins for jQuery isn’t a huge ordeal with a complex API. A diferencia de la mayoría de software, escribir plug-ins para jQuery no es una gran prueba con un complejo de la API. In fact, jQuery plug-ins are so easy to write that you might want to write a few to make your code even simpler. De hecho, jQuery plug-ins son tan fáciles de escribir que usted puede ser que desea escribir unos pocos para hacer su código más simple aún. Here’s the most basic jQuery plug-in you can write: Este es el más básico jQuery plug-in se puede escribir:

 $.fn.donothing = function(){ $. fn.donothing = function () (
     return this; este regreso;
 }; );

Although simple, this plug-in does require a bit of explanation. Aunque simple, este plug-in requiere un poco de explicación. First, to add a function to every jQuery object, you must assign it to $.fn . Next, this function must return this (the jQuery object) so that it doesn’t break method chaining . En primer lugar, para agregar una función a cada objeto jQuery, debe asignar a $.fn A continuación, esta función debe this este (el objeto jQuery), de modo que no se rompe método de encadenamiento.

You can easily build on top of this simple example. Usted puede construir fácilmente en la parte superior de este simple ejemplo. To write a plug-in to change the background instead of using css('background') , you use this: Para escribir un plug-in para cambiar el fondo en lugar de utilizar css('background') utilice la siguiente:

 $.fn.background = function(bg){ $. fn.background = function (bg) (
     return this.css('background', bg); this.css retorno ( «antecedentes», bg);
 }; );

Notice that I could just return the value from css() , because it already returns the jQuery object. Observe que sólo podría devolver el valor de css() porque ya jQuery devuelve el objeto. So, method chaining will still work fine. Por lo tanto, el método encadenar aún funcionan bien.

I recommend that you use jQuery plug-ins anytime you find that you repeat yourself. Yo recomiendo que use jQuery plug-ins en cualquier momento a encontrar que te repitas. For example, you might use a plug-in if you’re using the each() function to do the same thing over and over. Por ejemplo, podría usar un plug-in de si se está utilizando each() uno each() hacer la misma cosa una y otra vez.

Because jQuery plug-ins are so easy to write, hundreds of them are available for you to use. Debido a jQuery plug-ins son tan fáciles de escribir, cientos de ellos están disponibles para su uso. jQuery has plug-ins for tabs, rounded corners, slide shows, tool tips, date selectors, and probably anything else you can imagine. jQuery ha plug-ins para las pestañas, las esquinas redondeadas, presentaciones de diapositivas, herramienta de consejos, selectores de fecha, y probablemente cualquier cosa que usted puede imaginar. For a complete list of plug-ins, check out the Resources . Para obtener una lista completa de plug-ins, echa un vistazo a los recursos.

The most complex and most widely used plug-in is Interface, an animation plug-in that handles sorting, drag-and-drop functionality, complex effects, and other interesting and complex user interfaces (UIs). El más complejo y más ampliamente utilizado plug-in es Interface, una animación plug-in que se ocupa de la clasificación, arrastrar y soltar funcionalidad, efectos complejos, y otros interesantes y complejas interfaces de usuario (IEU). Interface is to jQuery what Scriptaculous is to Prototype. Interfaz es lo que jQuery Scriptaculous es un prototipo.

Also popular and useful is the Form plug-in, which allows you to easily submit a form in the background using Ajax. También popular y útil es la forma de plug-in, que le permite fácilmente presentar un formulario de antecedentes en el uso de Ajax. This plug-in takes care of the common situation in which you need to hijack the submit event of a form, then find all the different input fields and use them to construct an Ajax call. Este plug-in se encarga de la situación en la que usted necesita para secuestrar el caso de presentar un formulario y, después, todos los diferentes campos de entrada y utilizarlos para construir una llamada Ajax.


Life after jQuery La vida después de jQuery

I’ve only scratched the surface of what is possible with jQuery. Sólo he arañado la superficie de lo que es posible con jQuery. jQuery is fun to use, because you always learn new tricks and features that seem so natural. jQuery es divertido de usar, ya que siempre aprender nuevos trucos y características que parecen tan naturales. jQuery simplifies your JavaScript and Ajax programming completely from the first moment you use it; every time you learn something new, your code gets a bit simpler. simplifica su jQuery JavaScript y Ajax de programación completamente desde el primer momento de usarlo, cada vez que aprender algo nuevo, el código se un poco más simple.

After learning jQuery, I’ve had a lot more fun programming in the JavaScript language. Después de aprender jQuery, he tenido mucho más divertido de programación en el lenguaje JavaScript. All the boring stuff is taken care of, so I can focus on coding the juicy stuff. Todas las cosas aburridas se toma el cuidado de, por lo que puede centrarse en la codificación del material jugoso. With jQuery, I can barely remember the last time I wrote a for loop. Con jQuery, apenas puedo recordar la última vez que escribí un for I even cringe at the thought of working with other JavaScript libraries. I cringe incluso en la idea de trabajar con otras bibliotecas JavaScript. jQuery has honestly and truly changed the way I look at JavaScript programing forever. jQuery ha honesta y realmente cambió la forma me veo en la programación JavaScript para siempre.

Resources Recursos

Learn Aprender

  • developerWorks XML zone : Learn all about XML at the developerWorks XML zone. XML zona developerWorks: Aprenda todo acerca de XML en la zona developerWorks XML.
  • jQuery API documentation : Explore the complete documentation of jQuery with links to tutorials as well as the API reference. jQuery documentación de la API: Explore la documentación completa de jQuery con enlaces a tutoriales, así como la API de referencia.
  • jQuery tutorials : Check out a great collection of multilingual jQuery tutorials, including 40 in English. jQuery tutoriales: Echa un vistazo a una gran colección multilingüe de jQuery tutoriales, incluidos 40 en Inglés.
  • Visual jQuery : Read an interactive and easy-to-navigate jQuery API reference. Visual jQuery: Leer un interactivo y fácil de navegar jQuery API de referencia.
  • IBM XML certification :Find out how you can become an IBM-Certified Developer in XML and related technologies. Certificación de IBM XML: Descubra cómo usted puede convertirse en una IBM-Desarrollador Certificado en XML y las tecnologías conexas.
  • XML technical library : See the developerWorks XML Zone for a wide range of technical articles and tips, tutorials, standards, and IBM Redbooks. XML biblioteca técnica: Véase la Zona developerWorks XML para una amplia gama de artículos técnicos y consejos, tutoriales, normas, y Redbooks de IBM.

Get products and technologies Accede a los productos y tecnologías

  • jQuery : Visit the main jQuery site and download the source code. jQuery: Visite el sitio principal de jQuery y descargar el código fuente.
  • Selectors : Get a complete list of all the selectors you can use with jQuery, including CSS3 and XPath selectors. Selectores: Obtenga una lista completa de todos los selectores que puede utilizar con jQuery, incluyendo CSS3 y selectores XPath.
  • jQuery plug-ins : Find a nearly complete list of available jQuery plug-ins. jQuery plug-ins: Encuentra una casi completa lista de jQuery plug-ins.
  • Interface : Try the ultimate jQuery plug-in for animation, effects, drag-and-drop functionality, and UIs. Interfaz: Pruebe el último jQuery plug-in de animación, efectos de arrastrar y soltar funcionalidad, y el IEU.
  • Form plug-in : Get a jQuery plug-in that lets you submit a form using Ajax. Formulario de plug-in: Consigue un jQuery plug-in que te permite enviar un formulario utilizando Ajax.

Discuss Discutir

Sobre el autor original de artículo en inglés:

Foto de Jesse Skinner Jesse Skinner is a freelance Web developer specializing in JavaScript and CSS. Jesse Skinner es un desarrollador web independiente especializado en JavaScript y CSS. He spends his time expatriating from Canada to Germany, making the Web more fun to use, and unraveling the ancient mysteries of CSS browser compatibility. Pasa su tiempo expatriación de Canadá a Alemania, haciendo que la Web más divertido de usar, y descubrir los antiguos misterios de la compatibilidad del navegador CSS. If you’d like more information about Jesse or to read more about Web development, check out his blog at The Future of the Web . Si desea obtener más información acerca de Jesse o para leer más sobre el desarrollo Web, echa un vistazo a su blog en El futuro de la Web.

//Otro artículo interesante

jQuery helps you keep your code simple and succinct. jQuery le ayuda a mantener el código simple y sucinto. You no longer have to write a bunch of repetitious loops and DOM scripting library calls. Ya no tendrá que escribir un montón de bucles repetitivos y scripting DOM las llamadas a las bibliotecas. With jQuery, you can get right to the point and express yourself in the fewest possible characters. Con jQuery, puede obtener el derecho hasta el punto de expresarse y en el menor número posible de caracteres.

The jQuery philosophy is certainly unique: It’s designed to keep things simple and reusable. JQuery La filosofía es, sin duda, singular: Está diseñado para mantener las cosas simples y reutilizables. When you understand and feel comfortable with the philosophy, you’ll start to see just how much jQuery can improve the way you program. Cuando usted entienda y se sienta cómodo con la filosofía, usted comenzará a ver cuánto jQuery puede mejorar la forma en que usted programa.

Most introductions to jQuery focus on designers and inexperienced developers. I’m going to try to explain why jQuery should be of interest to experienced programmers as well.
Namespacing

The key to writing good, reusable JavaScript is to zealously manage your namespace. JavaScript provides a single global namespace (the window object), and many programmers (and some libraries) add symbols to this with abandon. Global variables are evil! Smart developers minimise their number of global objects, using techniques like the module pattern.

jQuery introduces just one symbol to the global namespace: the jQuery function/object. Everything else is either a directy property of jQuery or a method of the object returned by calls to the jQuery function.

What about language enhancements? Most libraries provide some variation of map, filter and strip, functions that are sadly missing from the JavaScript engines that ship with most browsers. Some libraries directly extend JavaScript’s built-in String and Array classes, but this can be a risky strategy. String.prototype and Array.prototype are themselves global namespaces, and adding properties to them brings the same risk of collisions as being careless with regular globals.

jQuery provides a number of language enhancement functions, but each one is made available as a property of the jQuery object: jQuery.each, jQuery.extend, jQuery.grep, jQuery.map, jQuery.merge and jQuery.trim. There’s no chance of these colliding with someone else’s code.
The infamous $ function

I wasn’t being entirely truthful when I said that jQuery was the only global symbol introduced: the $ symbol is also set up as a shortcut for jQuery. Thankfully, this is done in a non-destructive way: if you need your old $ function back (if you are already using code based on Prototype, for example) you can call jQuery.noConflict() to revert to the old $ function.
If you want the convenience of the $ function for jQuery without colliding with some other use of the global $ function, the jQuery documentation suggests the following idiom:

(function($) {
// Within this block, $ is a reference to jQuery
// Neat, huh?
})(jQuery);

Attaching everything to the $ symbol was one of the things that made me initially dismiss jQuery as a gimmick. For some reason thinking of it in terms of the jQuery symbol makes everything seem a lot more sensible, even though I’m happy to use the $ shortcut in my own code.
Selecting some elements

Every jQuery operation starts with selecting one or more nodes from the DOM. jQuery’s selection syntax (really a domain specific language) is an interesting hybrid of CSS 1, 2, bits of CSS 3, some XPath and a few custom extensions as well. I won’t describe it in detail here, but here are some useful examples:

jQuery(‘div.panel’)
All divs with class=“panel”
jQuery(‘p#intro’)
The paragraph with id=“intro”
jQuery(‘div#content a:visible’)
All visible links inside the div with id=“content”
jQuery(‘input[@name=email]’)
All input fields with name=“email”
jQuery(‘table.orders tr:odd’)
“odd” numbered rows in a table with class “orders”
jQuery(‘a[@href^=»http://»]’)
All external links (links that start with http://)
jQuery(‘p[a]’)
All paragraphs that contain one or more links

Of particular interest from the above are :visible and :odd, which are jQuery specific extensions. Also note that the attribute selectors use an @ sign, in common with XPath rather than CSS 2.

The selection language is extremely rich, and is similar to regular expressions in that time taken to learn it will pay off many times over.
Doing stuff with them

The object returned by a jQuery selector call is an interesting beast. It represents a collection of DOM elements, and behaves a bit like an array—it has a length property, items can be accessed by index and (most importantly) Firebug treats it as an array when displaying it in the interactive console. This is a clever illusion; the collection is actually a jQuery object, incorporating a large number of methods which can be used to query, modify and extend the collection of selected elements.

There are three principle categories of jQuery methods: those that manipulate all of the matched elements, those that return a value from the first matched object, and those that modify the selection itself.

I won’t list all of the methods (see visualjquery.com for that), but I’ll illustrate with some examples. If you have Firebug you can try these out interactively: use this Insert jQuery bookmarklet first to load the jQuery library in to any page, then paste the code examples in to the Firebug console.

jQuery(‘div#primary’).width(300);
Set the width of div id=“primary” to 300 px.
jQuery(‘p’).css(‘line-height’, ‘1.8em’);
Apply a line-height of 1.8em to all paragraphs.
jQuery(‘li:odd’).css({color: ‘white’, backgroundColor: ‘black’});
Apply two CSS rules to every other list item; note that the css() function can take an object instead of two strings.
jQuery(‘a[@href^=»http://»]’).addClass(‘external’).attr(‘target’, ‘_blank’);
Add a class of “external” to all external links (those beginning with http://), then add target=“_blank” for good measure. This makes use of chaining, described below.
jQuery(‘blockquote’).each(function(el) { alert(jQuery(this).text()) });
Iterate over every blockquote on the page, and alert its textual content (excluding HTML tags).
jQuery(‘a’).html(‘Click here!’);
Replace all link text on the page with the insidious “Click here!”.

Here are some examples of methods that read values from the first matched element:

var width = jQuery(‘div’).width();
How wide is the first div on the page?
var src = jQuery(‘img’).attr(‘src’);
What’s the src attribute of the first image on the page?
var color = jQuery(‘h1’).css(‘color’);
What colour is the first h1?

There’s a pleasing symmetry at work here: the methods used to set attributes (when passed two arguments, or an object representing multiple settings) can instead be used to read values if called with only one argument. This symmetry is used throughout jQuery, making the API much easier to commit to memory.

Finally, there are methods that modify the set of selected elements itself. Many of these also provide simpler ways of traversing the DOM:

jQuery(‘div’).not(‘[@id]’)
Returns divs that do not have an id attribute.
jQuery(‘h2’).parent()
Returns all elements that are direct parents of an h2.
jQuery(‘blockquote’).children()
Returns all elements that are children of a blockquote.
jQuery(‘p’).eq(4).next()
Find the fifth paragraph on the page, then find the next element (its direct sibling to the right).
jQuery(‘input:text:first’).parents(‘form’)
Find the form parent of the first input type=“text” field on the page. The optional argument to parents() is another selector.

Chaining

The jQuery team frequently boast about jQuery’s support of chaining, even to the point of declaring that “jQuery is designed to change the way that you write JavaScript” right on the front page. Personally I found this a big turn-off, so I’m happy to say that you can make good use of jQuery while avoiding lengthy chains of methods entirely.

That said, chaining can be used for some neat tricks. In addition to chaining a bunch of DOM manipulation methods together, you can use jQuery’s end() method to push and pop a stack of the selected element contexts. This is a little hard to explain; essentially, every time you use a method that changes the selected set of elements (such as children() or filter()) you can later use end() to revert back to the previous selection. Jesse Skinner gives a neat example of this in action in his tutorial Simplify Ajax development with jQuery:

$(‘form#login’)
// hide all the labels inside the form with the ‘optional’ class
.find(‘label.optional’).hide().end()
// add a red border to any password fields in the form
.find(‘input:password’).css(‘border’, ‘1px solid red’).end()
// add a submit handler to the form
.submit(function(){
return confirm(‘Are you sure you want to submit?’);
});

That whole thing is essentially a one-liner. It selects a form, finds some elements within that form, applies changes to them, reverts the selection back to the original form and assigns a submit() handler to it.

It’s a cute concept, but you don’t have to use it if you don’t want to. I’m quite happy splitting my code up with a few self-documenting variable names.
DOM manipulation

jQuery offers a few smart ways of making large scale manipulations to the DOM. The first is quite surprising: the jQuery function can take a snippet of HTML which it will turn in to a DOM element (it actually looks out for a string that starts with a less than sign):

var div = jQuery(‘

Some text

‘);

You can use chaining to add attributes to the div once it has been created:

var div = jQuery(‘

Some text

‘).addClass(‘inserted’).attr(‘id’, ‘foo’);

Now append it to the body tag:

div.appendTo(document.body)

Or prepend it to a known location using a selector:

div.prependTo(‘div#primary’)

Handling events

All JavaScript libraries need an event handling utility and jQuery’s is no exception. As with attr() and css(), the event methods serve dual purpose: call them with a function to assign an event handler; call them without to simulate that event being triggered:

jQuery(‘p’).click(function() { jQuery(this).css(‘background-color’, ‘red’); });
Set up paragraphs so that when you click them they turn red.
jQuery(‘p:first’).click()
Send a fake “click” to the first paragraph on the page.

Similar functions exist for the other browser events—mouseover, keyup and so on. Note that within an event handler the ’this’ keyword is set to the element that triggered the event; using jQuery(this) is a common idiom to enable jQuery methods on that element.

A couple of event related functions deserve a special mention:

jQuery(‘a’).hover(function() {
jQuery(this).css(‘background-color’, ‘orange’);
}, function() {
jQuery(this).css(‘background-color’, ‘white’);
});

hover() is a shortcut for setting up two functions that run onmouseover and onmouseout.

jQuery(‘p’).one(‘click’, function() { alert(jQuery(this).html()); });

one() sets up an event handler that will be removed after the first time it has been fired. The above example causes all paragraphs to alert their contents once the first time they are clicked.

jQuery also supports custom events, through the bind() and trigger() methods (for which click() and friends are just shortcuts). Custom events can take arguments, handled using an array passed to trigger():

jQuery(document).bind(‘stuffHappened’, function(event, msg) {
alert(‘stuff happened: ‘ + msg);
});
jQuery(document).trigger(‘stuffHappened’, [‘Hello!’]);

Unobtrusive scripting

This is a topic that is very dear to me. I still believe that the best Web applications are the ones that are still usable with scripting turned off, and that the best way to achieve that is through unobtrusive scripting, with events being assigned to elements after the regular page has been loaded (see Unobtrusive Scripting and Hijax for more).

jQuery has excellent support for this. Firstly, the node selection metaphor is core to both jQuery and unobtrusive scripting as a whole. Secondly, jQuery ships with a solution to the window.onload problem based on Dean Edwards’ work getting a “DOM loaded” event to work cross-browser. You can set a function up to run when the DOM is ready for it like so:

jQuery(document).ready(function() {
alert(‘The DOM is ready!’);
});

Even better, you can shortcut the above by passing your function directly to jQuery():

jQuery(function() {
alert(‘The DOM is ready!’);
});

jQuery and Ajax

jQuery has the best API for Ajax I’ve seen in any of the major libraries. The most simple form of an Ajax call looks like this:

jQuery(‘div#intro’).load(‘/some/fragment.html’);

This performs a GET request against /some/fragment.html and populates div#intro with the returned HTML fragment.

The first time I saw this, I was unimpressed. It’s a neat shortcut, but what if you want to do something more advanced like display an Ajax loading indicator? jQuery exposes custom events (ajaxStart, ajaxComplete, ajaxError and more) for you to hook in this kind of code. It also offers a comprehensive low-level API for more complex Ajax interactions:

jQuery.get(‘/some/script.php’, {‘name’: ‘Simon’}, function(data) {
alert(‘The server said: ‘ + data);
}); // GET against /some/script.php?name=Simon

jQuery.post(‘/some/script.php’, {‘name’: ‘Simon’}, function(data) {
alert(‘The server said: ‘ + data);
}); // POST to /some/script.php

jQuery.getJSON(‘/some.json’, function(json) {
alert(‘JSON rocks: ‘ + json.foo + ‘ ‘ + json.bar);
}); // Retrieves and parses /some.json as JSON

jQuery.getScript(‘/script.js’); // GET and eval() /script.js

Plugins

Considering the amount of functionality you get out of the box, jQuery is actually pretty small—it comes in at 20KB when minified, even smaller when gzipped. Additional functionality outside the framework is handled using plugins, which can (and do) add brand new methods to the existing jQuery instance object. If you want to be able to run:

jQuery(‘p’).bounceAroundTheScreenAndTurnGreen();

jQuery’s plugin mechanism provides documented hooks for adding that method to the jQuery system. The ease with which these can be created has attracted an impressive community of plugin authors; the Plugin directory lists well over 100.

One really nice touch is that you can add custom selectors in a similar way to custom methods. The moreSelectors plugin adds things like “div:color(red)” to match divs with red text, for example.
Leaky abstractions

In my new-found respect for jQuery, I’ve been struggling with one philosophical blocker. For the past few years, I’ve been advising people to only pick a JavaScript library if they were willing to read the source code and figure out exactly how it works. My reasoning was based on Joel Spolsky’s classic essay The Law of Leaky Abstractions, which points out that the more complexity your APIs are hiding, the more trouble you’ll be in when some of that complexity leaks through. Browsers are the leakiest abstraction of them all, so being able to dig yourself out of a hole when the library fails to cover for you is of paramount importance.

jQuery uses some really arcane tricks to achieve its functionality—parts of it (like the selector code) are positively terrifying. If understanding exactly how the library works is necessary, jQuery must be a poor choice for the majority of developers. However, the enormous popularity of jQuery combined with a distinct lack of horror stories demonstrates that this is not the case.

I think I’m going to have to reconsider my advice. The way the library works isn’t the issue: it’s understanding the underlying issues, and knowing what kind of browser differences there are and what kind of techniques your library is using to fix them. No library can protect you 100% against weird browser behaviour, but as long as you have a grounding in the underlying theory you should be able to figure out if a problem stems from your own code, your library or the underlying implementation.
To conclude

I hope I’ve made the case that jQuery isn’t just another library—there are enough interesting ideas in there to teach even the most hardened of JavaScript programmers some new tricks. Even if you don’t intend on using it, it’s still worth spending some time exploring the jQuery ecosystem.

Everithing was posted in: http://simonwillison.net/2007/Aug/15/jquery/

http://www-128.ibm.com/developerworks/library/x-ajaxjquery.html