====== jQuery ======
Es una pequeña pero potente librería para agilizar las acciones de JavaScript sobre el DOM de la página, que se basa en el enlace de funciones a eventos o acciones del DOM.
===== Básico =====
==== Utilización ====
Para utilizarlo en nuestro código indicaremos en una tag script habiendo incluido previamente el archivo que contiene jquery en la ruta seleccionada:
...
==== Cuando se carga el documento ====
Podemos ejecutar una función cuando el documento esté preparado para ser manipulado, para ello utilizamos ''$(document).ready'' e indicamos la función deseada:
$(document).ready(
function() {
alert("El DOM está preparado");
}
);
===== Acceso a los elementos =====
==== Las distintas opciones ====
A partir del identificador:
$("#identificador")
A partir del tipo de etiqueta:
$("a")
A partir de su clase:
$(".codigo")
=== Ejemplos ===
Dentro de esta función ''ready'' podemos indicar las cosas que queremos que ocurran cuando, por ejemplo, se haga click sobre un enlace. El siguiente código hace que al pulsar sobre cualquiera de los links aparezca un mensaje:
$(document).ready(function() {
$("a").click(function(){
alert ("Click en un enlace");
});
});
Desde las funciones podemos acceder también a código jQuery del elemento mediante ''$this.''
$(document).ready(function() {
$("a").click(function(){
$this.hide();
});
});
==== Encadenamiento ====
El encadenamiento corresponde a la cualidad de jQuery para escoger a cual de los elementos del DOM va a recibir la acción mediante los métodos ''filter'', que indica el elemento, o ''end'' que finaliza el encadenamiento.
$(document).ready(function() {
$("a")
.filter(".clickme")
.click(function(){
...
})
.end()
.filter(".hideme")
.click(function(){
...
})
.end();
});
I give a message when you leaveClick me to hide!I'm a normal link
En este caso el string que se le pasa a filter es "''.nombre''", corresponde al identificador de clase del elemento. Si quisieramos indcarlo por la propiedad id haríamos "''#nombre''".
==== Acceso a las propiedades ====
Acceso (asignación y lectura) al valor de un ''input'':
$("#TextBox1").val("defg");
alert($("#TextBox1").val());
Acceso (asignación y lectura) de la propiedad ''innerHtml'':
$("#test").html("Hello Again");
alert($("#test2").html());
Acceso al texto interno:
$('#divNombre').text();
==== Encontrar elementos anidados ====
Realizar una función para cada elemento div dentro de otro elemento:
$('#lTags').find("div").each(function() {
$(this)...
});
Encontrar cuantos elementos div tiene internamente otro elemento:
$('#lTags').find("div").size();
Encontrar los checkbox activos en otro elemento:
$(this).find("input[type=checkbox][checked]")
==== Acceso a los estilos ====
Para mirar el estilo de un elemento:
var weight = $("#myElement").css("text-weight");
Para escribirlo:
$("#myElement").css("text-weight", "bold");
Podemos agregar y elimar clases de un elementos mediante las funciones ''removeClass('className')'' y ''addClass('className')''.
===== Funciones =====
==== Agregar elementos ====
Con la función ''append'':
$('
hello<\/div>').appendTo(document.body);
==== Acceder a sus propiedades ====
... Con la función ''attr'':
$("#MyImg").attr({
src: "/images/hat.gif",
title: "jQuery",
alt: "jQuery Logo"
});
$(idLbl).attr("style", "color:orange;");
var txtImg = $("").attr("alt");
==== Otras funciones ====
* ''jQuery.trim(str)'' permite realizar un trim del string pasado.
var user = $("#add_user").val();
user = jQuery.trim(user);
if (user !== "") {
...
* ''index()'' te dice el índice de un elemento dentro de su contenedor.
$("#tags li").click(function(){
alert( "Hi, I'm element " + $(this).index() );
});
* ''remove()'' elimina el elemento.
$("#divID").remove();
===== Eventos =====
Cuando la función enlazada corresponde a un evento lo indicaremos recibiendo un parámetro en la función, por ejemplo en el envento click:
$("a").click(function(event){
alert("Se ha producido un evento");
});
Para el ''keypress'':
$("#add_user").keypress (function (event) {
if (event.keyCode == '13') {
event.preventDefault();
$("#btn").click();
}
});
Para lanzar un evento:
$("#btn").click();
$("#txt").change();
==== Detener los eventos ====
Podemos impedir que un evento siga ejecutándose añadiendo ''event.preventDefault();'' a la función enlazada a este:
$("a").click(function(event){
event.preventDefault();
alert("Se ha detenido el evento");
});
===== Efectos a los CSS =====
Si tenemos declarado en el documento algo parecido a lo siguiente:
Podremos añadir a los links este estilo mediante ''addClass'' o eliminar dicho estilo con ''removeClass'':
.filter("#hideme")
.click(function(){
$(this).addClass("test");
})
.end()
===== Efectos =====
==== Ocultar ====
Mediante la función ''hide'', la cual, si recibe el parámetro ''slow'' lo hará paulatinamente:
$("a").click(function(event){
event.preventDefault();
$(this).hide("slow");
});
... o ...
$("a").click(function(event){
$(this).hide();
});
===== Controles =====
==== Select ====
=== Coger el valor seleccionado (o los valores) ===
$("select#combo").val();
=== Controlar cuando cambia ===
$("select#" + idCtrlLine).change(function() { ... }
=== Borrar todas las options de un select ===
$("select#" + idCtrlTrajecte).html('');
=== Borrar una option concreta ===
$("#myId").find("option[value='myValue']").remove();
=== Seleccionar el tercer elemento ===
$("select#" + idCtrlTrajecte + " option").eq(2).attr("selected", "selected");
=== Montar un select a partir de un json ===
$.getJSON(url, function(data) {
var options = '';
for (var i = 0; i < data.length; i++) {
options += '';
}
$("select#" + idCtrlTrajecte).html(options);
});
=== Coger el texto del elemento seleccionado ===
var text = $('#scombo :selected').text();
==== Input text ====
=== Detectar pulsaciones de tecla ===
A partir de los eventos: ''keyup'', ''keydown'':
$("#myInput").keydown(function(event){
alert ($(this).val());
}
==== Tablas ====
Para recoger las celdas de una fila utilizaremos la función ''children'' pasándole el tag que nos interesa:
$('#tableResult tr').click(function() {
var id = $(this).children('td').eq(0).text();
var txt = id + ", " + $(this).children('td').eq(1).text();
});
==== Checkbox ====
Saber si un checkbox está ''checked'':
var showUnTagged = $("#chkUnTagged").attr("checked");
==== Radio Buttons ====
Saber qué radio está ''checked'' en el grupo "mode":
$("input[@name='mode']:checked").val()
Siendo los radios:
AND
OR
===== AJAX =====
* :!: Ten en cuenta que no están permitidas las llamadas entre sitios cruzados. Es decir, de un dominio a otro.
Para acceder al módulo de AJAX de jQuery haremos:
$.ajax({});
Entre los corchetes irán los parámetros que pueden ser:
* **async**, que indica cómo será la carga del objeto AJAX (síncrona (bloquea el navegador hasta tenerlo) o asíncrona), acepta ''true'' o ''false''.
* **beforeSend** indica el nombre de la función a llamar antes de realizar la llamada AJAX.
* **complete**, el nombre de la función que se llamará cuando la llamada AJAX esté completa, los parámetros que recibirá serán el objeto XMLHttpRequest y un string con el resultado de la operación.
* **contentType**
* **data** especifica los dataos que se enviarán (por ejemplo ''foo=bar&foo2=bar2;'').
* **dataType** indica el tipo de datos que vendrán (xml, html, script, json).
* **error**, función que se ejecuta cuando hay un error.
* **global**
* **ifModified**
* **processData**
* **success**, función que se ejecutará si todo ha ido bien, recibe como parámetro los datos.
* **timeout** permite indicar el tiempo de espera.
* **type** indica si el modo de conexión es ''GET'' o ''POST''.
* **url** dirección donde están los datos.
Por ejemplo: \\
Muestra los datos que han llegado en un ''alert'':
$.ajax({
url: "mi-pagina-cool.html",
success: function(datos){
alert(datos);
}
});
Si indicamos que los datos son ''dataType: "json"'' en el parámetro de la función ya vendrá directamente el objeto javascript:
$(document).ready(
function() {
$.ajax({
url: "controller.ashx",
dataType: "json",
success: function(datos) {
$("#TextBox1").val(datos.name);
}
});
}
);
==== Otras formas ====
=== Función getJSON ===
Función que recoge datos en formato json y devuelve el objeto javascript:
$.getJSON("controller.ashx",
function(data) {
$("#TextBox1").val(data.name);
});
=== Utilizando get() ===
$.get("demo_test.asp",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
=== Función load ===
Carga los datos de un archivo sobre una etiqueta con el identificador indicado:
$("#entryContent").load("./controllers/entry.ashx?id="+entry);
$("#entryContent").load("./controllers/entry.ashx?id="+entry, function () {
alert('it was fine!');
});
=== Enviar datos con post() ===
$.post("test.php", { name: "John", time: "2pm" }, dataType="json" );
===== Plugins =====
==== Ejemplos ====
=== Boilerplate ===
// jQuery Plugin Boilerplate
// A boilerplate for kick-starting jQuery plugins development
// version 1.3, May 07th, 2011
// by Stefan Gabos
// with help from Roger Padilla, Shinya, JohannC, Steven Black, Rob Lifford
// remember to change every instance of "pluginName" to the name of your plugin!
(function($) {
// here it goes!
$.fn.pluginName = function(method) {
// public methods
// to keep the $.fn namespace uncluttered, collect all of the plugin's methods in an object literal and call
// them by passing the string name of the method to the plugin
//
// public methods can be called as
// element.pluginName('methodName', arg1, arg2, ... argn)
// where "element" is the element the plugin is attached to, "pluginName" is the name of your plugin and
// "methodName" is the name of a function available in the "methods" object below; arg1 ... argn are arguments
// to be passed to the method
//
// or, from inside the plugin:
// methods.methodName(arg1, arg2, ... argn)
// where "methodName" is the name of a function available in the "methods" object below
var methods = {
// this the constructor method that gets called when the object is created
init : function(options) {
// the plugin's final properties are the merged default and user-provided properties (if any)
// this has the advantage of not polluting the defaults, making them re-usable
this.pluginName.settings = $.extend({}, this.pluginName.defaults, options);
// iterate through all the DOM elements we are attaching the plugin to
return this.each(function() {
var $element = $(this), // reference to the jQuery version of the current DOM element
element = this; // reference to the actual DOM element
// code goes here
});
},
// a public method. for demonstration purposes only - remove it!
foo_public_method: function() {
// code goes here
}
}
// private methods
// these methods can be called only from inside the plugin
//
// private methods can be called as
// helpers.methodName(arg1, arg2, ... argn)
// where "methodName" is the name of a function available in the "helpers" object below; arg1 ... argn are
// arguments to be passed to the method
var helpers = {
// a private method. for demonstration purposes only - remove it!
foo_private_method: function() {
// code goes here
}
}
// if a method as the given argument exists
if (methods[method]) {
// call the respective method
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
// if an object is given as method OR nothing is given as argument
} else if (typeof method === 'object' || !method) {
// call the initialization method
return methods.init.apply(this, arguments);
// otherwise
} else {
// trigger an error
$.error( 'Method "' + method + '" does not exist in pluginName plugin!');
}
}
// plugin's default options
$.fn.pluginName.defaults = {
foo: 'bar'
}
// this will hold the merged default and user-provided options
// you will have access to these options like:
// this.pluginName.settings.propertyName from inside the plugin or
// element.pluginName.settings.propertyName from outside the plugin, where "element" is the element the
// plugin is attached to;
$.fn.pluginName.settings = {}
})(jQuery);
Uso:
$(document).ready(function() {
// attach the plugin to an element
$('#element').pluginName({'foo': 'bar'});
// call a public method
$('#element').pluginName('foo_public_method');
// get the value of a property
$('#element').pluginName.settings.foo;
});
=== Ejemplo ===
(function($){
$.fn.myplugin = function(options){
var defaults = {
myval: 1,
mycolor: 'blue',
storeValue: '#myInput'
},
settings = $.extend({}, defaults, options);
return this.each(function(){
$(this).click(function(){
doSomething();
});
});
function doSomething(){
$(settings.storeValue).val(settings.mycolor);
}
};
})(jQuery);
=== Asignar datos independientemente ===
// set 'options' for '#div2'
$("#div2").data('options', {width: 500, height: 500});
// get 'options' for '#div2' (this would be in your plugin code)
var opts = $('#div2').data('options');
alert('options.height:' + opts.height + '\n'
'options.width:' + opts.width);
$("#div2").data('priority', 2);
$("#div2").data('flagColors', ['red', 'white', 'blue']);
$("#div2").data('parts', {arm: 2, legs: 2});
// ...and retrieve it later like so:
var foo = $("#div2").data('priority');
var foo2 = $("#div2").data('flagColors');
var foo3 = $("#div2").data('parts');
=== Más ejemplos ===
* {{:fw:others:example_plugin_adding.txt.zip|}}
===== Como... =====
==== Leer un xml ====
* http://www.webmonkey.com/tutorial/Easy_XML_Consumption_using_jQuery?oldid=20032, o esta web descargada ({{fw:others:easyxml.tar.gz|}}(borrar si deja de ser útil))
Básicamente...
* Leer un archivo xml:
{{fw:others:jquery_xml_1.png|}}
* Leer los atributos de una etiqueta:
{{fw:others:jquery_xml_2.png|}}
* Modificar el xml:
{{fw:others:jquery_xml_3.png|}}
=== Notas ===
* No puedes utilizar el método ''.html()'' para recoger el código interno de un elemento que está dentro de un documento .xml en el servidor ya que este devuelve el documento como un ''XMLObject'' y en dicho objeto eso no está permitido. Aún así puedes engañar al servidor simplemente cambiando la extensión del archivo por, por ejemplo, .txt.
==== Lanzar un evento ====
Mediante la función ''trigger''. En el siguiente ejemplo se recoge el click en una fila de una tabla, esta contiene un checkbox y lo que hace es que, al recoger dicho click se lanza el click sobre el checkbox:
$(document).ready(function() {
$('#rowclick2 tr').click(function(event) {
$(this).toggleClass('selected');
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
});
==== Pequeños ====
=== Preguntar si un elemento existe ===
jQuery.fn.exists = function(){return jQuery(this).length>0;}
if ($(selector).exists()) {
...
}
O si el ''length'' es 0:
$('#myImg').length
=== Crear\añadir fácilmente elementos ===
var $option = $("").text(d.pnom).val(d.id).attr("selected", true);
$("#listUsers").append($option).change();
===== Notas =====
* Callbacks más organizados:
$("#myButton").click( callbacks.myFunctionOne );
$("#otherButton").click( callbacks.myFunctionTwo );
var callbacks = {
myFunctionOne: function( event ) { }
myFunctionTwo: function( event ) { }
}