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.
Para utilizarlo en nuestro código indicaremos en una tag script habiendo incluido previamente el archivo que contiene jquery en la ruta seleccionada:
<html> <head> <script type="text/javascript" src="./jquery.js"></script> <script type="text/javascript"> // Código jquery </script> </head> ...
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"); } );
A partir del identificador:
$("#identificador")
A partir del tipo de etiqueta:
$("a")
A partir de su clase:
$(".codigo")
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(); }); });
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(); });
<a href="http://google.com/" class="clickme">I give a message when you leave</a> <a href="http://yahoo.com/" class="hideme">Click me to hide!</a> <a href="http://microsoft.com/">I'm a normal link</a>
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 (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("<span class='red'>Hello <b>Again</b></span>"); alert($("#test2").html());
Acceso al texto interno:
$('#divNombre').text();
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]")
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').
Con la función append:
$('<tr><td>hello<\/td><td>hello<\/td><td>hello<\/td><\/tr>').appendTo("#tableResult tbody"); $('<div>hello<\/div>').appendTo(document.body);
… 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");
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();
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();
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"); });
Si tenemos declarado en el documento algo parecido a lo siguiente:
<style type="text/css">a.test { font-weight: bold; } </style>
Podremos añadir a los links este estilo mediante addClass o eliminar dicho estilo con removeClass:
.filter("#hideme") .click(function(){ $(this).addClass("test"); }) .end()
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(); });
$("select#combo").val();
$("select#" + idCtrlLine).change(function() { ... }
$("select#" + idCtrlTrajecte).html('');
$("#myId").find("option[value='myValue']").remove();
$("select#" + idCtrlTrajecte + " option").eq(2).attr("selected", "selected");
$.getJSON(url, function(data) { var options = ''; for (var i = 0; i < data.length; i++) { options += '<option value="' + data[i].id + '">' + data[i].denominacion+ '</option>'; } $("select#" + idCtrlTrajecte).html(options); });
var text = $('#scombo :selected').text();
A partir de los eventos: keyup, keydown:
$("#myInput").keydown(function(event){ alert ($(this).val()); }
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(); });
Saber si un checkbox está checked:
var showUnTagged = $("#chkUnTagged").attr("checked");
Saber qué radio está checked en el grupo “mode”:
$("input[@name='mode']:checked").val()
Siendo los radios:
<input type="radio" name="mode" value="and" /> AND <input type="radio" name="mode" value="or" /> OR
Para acceder al módulo de AJAX de jQuery haremos:
$.ajax({});
Entre los corchetes irán los parámetros que pueden ser:
true o false.foo=bar&foo2=bar2;).GET o POST.
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); } }); } );
Función que recoge datos en formato json y devuelve el objeto javascript:
$.getJSON("controller.ashx", function(data) { $("#TextBox1").val(data.name); });
$.get("demo_test.asp",function(data,status){ alert("Data: " + data + "\nStatus: " + status); });
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!'); });
$.post("test.php", { name: "John", time: "2pm" }, dataType="json" );
// 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; });
(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);
// 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');
Básicamente…
.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.
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'); } }); });
jQuery.fn.exists = function(){return jQuery(this).length>0;} if ($(selector).exists()) { ... }
O si el length es 0:
$('#myImg').length
var $option = $("<option></option>").text(d.pnom).val(d.id).attr("selected", true); $("#listUsers").append($option).change();
$("#myButton").click( callbacks.myFunctionOne ); $("#otherButton").click( callbacks.myFunctionTwo ); var callbacks = { myFunctionOne: function( event ) { } myFunctionTwo: function( event ) { } }