Añadir función jQuery a elementos específicos


Sé que puede agregar nuevas funciones de jQuery mediante $.fn.someFunction = function()

Sin embargo, solo quiero agregar funciones a elementos específicos. Probé esta sintaxis y no funciona $('.someElements').fn.someFunction = function()

Quiero hacer esto para poder llamar a la función de esta manera en algún lugar del código $('someElements').someFunction();

Author: peter, 2011-01-17

9 answers

Uso .bind() y .trigger()

$('button').bind('someFunction',function() {
    alert('go away!')
});


$('button').click(function(){
    $(this).trigger('someFunction');
});

A partir de jQuery 1.7, el .el método on() es el método preferido para adjuntar controladores de eventos a un documento.

 42
Author: Reigel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-04 15:32:51

Puedes hacer lo anterior con esto:

$.fn.testFn = function(){
    this.each(function(){
        var className = $(this).attr('class');
        $(this).html(className);
    });    
};

$('li').testFn(); //or any element you want

Prueba: http://jsfiddle.net/DarkThrone/nUzJN /

 18
Author: DarkThrone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-17 03:49:21

Yo, necesitaba hacer lo mismo, se le ocurrió esto. su buena causa destruir el elemento y la función va poof! Creo...

var snippet=jQuery(".myElement");
snippet.data('destructor', function(){
    //do something
});
snippet.data('destructor')();
 9
Author: Drizzel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-05 15:25:48

La respuesta de@Reigel es genial! Sin embargo, también puede usar la sintaxis $.fn y dejar que su función solo maneje ciertos elementos:

$.fn.someFunction = function(){
    this.each(function(){
        // only handle "someElement"
        if (false == $(this).hasClass("someElement")) {
            return; // do nothing
        }

        $(this).append(" some element has been modified");

        return $(this); // support chaining
    });    
};

// now you can call your function like this
$('.someElement').someFunction();            

Véase el artículo de trabajo: http://jsfiddle.net/AKnKj/3 /

 7
Author: Friederike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-14 08:47:33

En realidad también tenía este caso de uso, pero con un objeto en caché. Así que ya tenía un objeto jQuery, un menú conmutable, y quería adjuntar dos funciones a ese objeto, "abrir"y " cerrar". Las funciones necesarias para preservar el alcance del elemento en sí y eso era todo, así que quería this ser el objeto menu. De todos modos, puede agregar funciones y variables de cualquier manera, al igual que cualquier otro objeto javascript. A veces lo olvido.

var $menu = $('#menu');
$menu.open = function(){
   this.css('left', 0);
   this.is_open = true; // you can also set arbitrary values on the object
};
$menu.close = function(){
   this.css('left', '-100%');
   this.is_open = false;
};

$menu.close();
 6
Author: charltoons,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-26 01:22:20

Si desea esta función solo para selectores particulares, lo siguiente funcionará para usted. Acabo de tener un escenario donde he necesitado esto y funciona muy bien.

$('.my-selector').each(function(){

    $(this).init.prototype.getUrl = function(){
        // do things
    };
})

Luego más tarde puedes hacer

$('.my-selector').getUrl()

Sin tener que definirlo como un complemento, o usar datos o eventos de enlace/on/trigger.

Obviamente, puede cambiar la función para devolver el objeto que lo contiene si desea usarlo en el encadenamiento devolviendo this

$('.my-selector').each(function(){

    $(this).init.prototype.getUrl = function(){
        // do things
        return this;
    };
})
 5
Author: dan richardson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-11 07:14:51

La solución más obvia es asignar una función como propiedad del objeto:

obj.prop("myFunc", function() {
  return (function(arg) {
    alert("It works! " + arg);
  });
});

Luego llámelo en el objeto de esta manera:

obj.prop("myFunc")("Cool!");

Nota: su función es el valor de retorno de la externa, véase: http://api.jquery.com/prop/#prop-propertyName-function

 2
Author: Snegh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-27 18:05:04

No estoy seguro con mi respuesta si esto le ayudará, pero solo un intento de cómo usar .¿vivir?

$(selector).live(click,function(){
    //some codes here
});
 0
Author: Carls Jr.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-31 04:13:20

Hice esto y está funcionando bien..

 function do_write(){
     $("#script").append("<script> $(\'#t"+(id_app+4)+"\').change(function(){  alert('Write Your Code here');    });<\/script>");
     console.log("<script> $(\'#t"+(id_app+4)+"\').change(function(){  alert('hello');    });<\/script>");
}

Y llame a la función desde su función dinámica que está creando un control dinámico en html

 -1
Author: dsk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-28 06:05:56