2012-06-18 27 views
0

我想创建一个函数inject(),我可以调用任何jQuery的DOM对象。我怎样才能原型的jQuery“DOM”类

例如,$('div').inject(),$('#abc').inject()或甚至$('nonStandardElement').inject();

我需要原型,因为它应该适用于尚未创建的元素。

我可以通过什么样的类(或一组类)来完成这个任务?

+2

您可以使用jQuery定义插件。检查出http://docs.jquery.com/Plugins/Authoring#Getting_Started,除非你坚持原型功能 – frictionlesspulley

回答

1

这就是所谓的jQuery plugin。您将方法添加到jQuery的原型对象,该对象以jQuery.fn的形式公开:

jQuery.fn.inject = function inject() { 
    /* do what you want */ 
    return this; // for chainability 
}; 
+0

fn优于原型的优势是什么? –

+0

这是官方的:-)从源头上:'jQuery.fn = jQuery.prototype = {...}' – Bergi

0

没关系,想通了!

原来我可以添加它的权利到 'jQuery的' 对象,如

jQuery.prototype.inject = function(x){alert('x')} 
0

您可以编写自己的jQuery插件这样,

(function($){ 
$.fn.inject= function() { 

//code... 
}; 
})(jQuery); 
//Sample call 
    $(selector).inject();