Herramientas de usuario

Herramientas del sitio


fw:others:jquery

Diferencias

Muestra las diferencias entre dos versiones de la página.

Enlace a la vista de comparación

Ambos lados, revisión anterior Revisión previa
Próxima revisión
Revisión previa
fw:others:jquery [2010/03/09 16:29]
alfred
fw:others:jquery [2020/05/09 09:25] (actual)
Línea 88: Línea 88:
 </​code>​ </​code>​
 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''"​. 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''"​.
 +
  
  
Línea 106: Línea 107:
 alert($("#​test2"​).html());​ alert($("#​test2"​).html());​
 </​code>​ </​code>​
- +Acceso al texto interno: 
- +<code javascript>​ 
- +$('#​divNombre'​).text();​ 
 +</​code>​
  
 ==== Encontrar elementos anidados ==== ==== Encontrar elementos anidados ====
Línea 126: Línea 127:
 $(this).find("​input[type=checkbox][checked]"​) $(this).find("​input[type=checkbox][checked]"​)
 </​code>​ </​code>​
 +
 ==== Acceso a los estilos ==== ==== Acceso a los estilos ====
 Para mirar el estilo de un elemento: Para mirar el estilo de un elemento:
Línea 135: Línea 137:
 $("#​myElement"​).css("​text-weight",​ "​bold"​);​ $("#​myElement"​).css("​text-weight",​ "​bold"​);​
 </​code>​ </​code>​
 +Podemos agregar y elimar clases de un elementos mediante las funciones ''​removeClass('​className'​)''​ y ''​addClass('​className'​)''​.
 +
  
 ===== Funciones ===== ===== Funciones =====
 +
  
 ==== Agregar elementos ==== ==== Agregar elementos ====
Línea 144: Línea 149:
 $('<​div>​hello<​\/​div>'​).appendTo(document.body);​ $('<​div>​hello<​\/​div>'​).appendTo(document.body);​
 </​code>​ </​code>​
 +
 ==== Acceder a sus propiedades ==== ==== Acceder a sus propiedades ====
 ... Con la función ''​attr'':​ ... Con la función ''​attr'':​
Línea 154: Línea 160:
 $(idLbl).attr("​style",​ "​color:​orange;"​);​ $(idLbl).attr("​style",​ "​color:​orange;"​);​
 var txtImg = $(""​).attr("​alt"​);​ var txtImg = $(""​).attr("​alt"​);​
 +</​code>​
 +
 +
 +
 +==== Otras funciones ====
 +  * ''​jQuery.trim(str)''​ permite realizar un trim del string pasado.
 +<code javascript>​
 +var user = $("#​add_user"​).val();​
 +user = jQuery.trim(user);​
 +if (user !== ""​) {
 +...
 +</​code>​
 +
 +  * ''​index()''​ te dice el índice de un elemento dentro de su contenedor.
 +<code javascript>​
 +$("#​tags li"​).click(function(){
 +    alert( "Hi, I'm element " + $(this).index() );
 +});
 +</​code>​
 +
 +  * ''​remove()''​ elimina el elemento.
 +<code javascript>​
 +$("#​divID"​).remove();​
 </​code>​ </​code>​
  
Línea 163: Línea 192:
 }); });
 </​code>​ </​code>​
- +Para el ''​keypress'':​ 
- +<code javascript>​ 
 +$("#​add_user"​).keypress (function (event) { 
 +    if (event.keyCode == '​13'​) ​ { 
 +      event.preventDefault();​ 
 +      $("#​btn"​).click();​ 
 +    } 
 +}); 
 +</​code>​ 
 +Para lanzar un evento: 
 +<code javascript>​ 
 +$("#​btn"​).click();​ 
 +$("#​txt"​).change();​ 
 +</​code>​
  
 ==== Detener los eventos ==== ==== Detener los eventos ====
Línea 212: Línea 252:
  
 ===== Controles ===== ===== Controles =====
 +
  
  
Línea 220: Línea 261:
  
 ==== Select ==== ==== Select ====
-=== Coger el valor seleccionado ===+=== Coger el valor seleccionado ​(o los valores) ​===
 <code javascript>​ <code javascript>​
 $("​select#​combo"​).val();​ $("​select#​combo"​).val();​
Línea 290: Línea 331:
  
 ===== AJAX ===== ===== 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: Para acceder al módulo de AJAX de jQuery haremos:
 <​code>​ <​code>​
Línea 333: Línea 376:
 ); );
 </​code>​ </​code>​
 +
  
 ==== Otras formas ==== ==== Otras formas ====
Línea 343: Línea 387:
     });     });
 </​code>​ </​code>​
 +=== Utilizando get() === 
 +<code javascript>​ 
 +$.get("​demo_test.asp",​function(data,​status){ 
 +  alert("​Data:​ " + data + "​\nStatus:​ " + status); 
 +}); 
 +</​code>​
 === Función load === === Función load ===
 Carga los datos de un archivo sobre una etiqueta con el identificador indicado: Carga los datos de un archivo sobre una etiqueta con el identificador indicado:
Línea 352: Línea 401:
 }); });
 </​code>​ </​code>​
 +=== Enviar datos con post() ===
 +<code javascript>​
 +$.post("​test.php",​ { name: "​John",​ time: "​2pm"​ }, dataType="​json"​ );
 +</​code>​
 +===== Plugins =====
 +==== Ejemplos ====
  
 +=== Boilerplate ===
 +<code javascript>​
 +// 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);
 +</​code>​
 +Uso:
 +<code javascript>​
 +$(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;​
 +
 +});
 +</​code>​
 +=== Ejemplo ===
 +<code javascript>​
 +(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);
 +</​code>​
 +=== Asignar datos independientemente ===
 +<code javascript>​
 +// 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'​);​
 +</​code>​
 +=== Más ejemplos ===
 +  * {{:​fw:​others:​example_plugin_adding.txt.zip|}}
 ===== Como... ===== ===== Como... =====
  
Línea 383: Línea 577:
       });       });
 </​code>​ </​code>​
 +
 +
  
 ==== Pequeños ==== ==== Pequeños ====
Línea 395: Línea 591:
 <code javascript>​ <code javascript>​
 $('#​myImg'​).length $('#​myImg'​).length
 +</​code>​
 +=== Crear\añadir fácilmente elementos ===
 +<code javascript>​
 +var $option = $("<​option></​option>"​).text(d.pnom).val(d.id).attr("​selected",​ true);
 +$("#​listUsers"​).append($option).change();​
 +</​code>​
 +===== Notas =====
 +  * Callbacks más organizados:​
 +<code javascript>​
 +$("#​myButton"​).click( callbacks.myFunctionOne );
 +$("#​otherButton"​).click( callbacks.myFunctionTwo );
 +
 +var callbacks = {
 +  myFunctionOne:​ function( event ) {  }
 +  myFunctionTwo:​ function( event ) {  }
 + 
 +}
 </​code>​ </​code>​
  
fw/others/jquery.1268152143.txt.gz · Última modificación: 2020/05/09 09:24 (editor externo)