最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add functions to some jQuery objects, but not others? - Stack Overflow

programmeradmin1浏览0评论

Let's say I have a <ul> list:

<ul class="products">
    ...
</ul>

I want to select it with jQuery, then add some functions to that object. For example, I'd like to add an addProduct(productData) function and a deleteProduct(productId) function. However, I'd like the functions to only be added to the object that's returned by the selector. So for example, something like this:

var productList = $.extend($('ul.products'), {
    addProduct: function(productData) {
        // add a new li item
    },
    deleteProduct: function(productId) {
        // delete li with id
    }
});

How would I do this using jQuery? The key point here is that I only want to add the functions to an instance returned by a jQuery selector. In other words, I don't want to modify jQuery's prototype or create a plugin, since those will make the functions available across everything, whereas I only want to add the functions to one specific instance.

Let's say I have a <ul> list:

<ul class="products">
    ...
</ul>

I want to select it with jQuery, then add some functions to that object. For example, I'd like to add an addProduct(productData) function and a deleteProduct(productId) function. However, I'd like the functions to only be added to the object that's returned by the selector. So for example, something like this:

var productList = $.extend($('ul.products'), {
    addProduct: function(productData) {
        // add a new li item
    },
    deleteProduct: function(productId) {
        // delete li with id
    }
});

How would I do this using jQuery? The key point here is that I only want to add the functions to an instance returned by a jQuery selector. In other words, I don't want to modify jQuery's prototype or create a plugin, since those will make the functions available across everything, whereas I only want to add the functions to one specific instance.

Share Improve this question edited May 23, 2013 at 9:56 Matt 75.3k26 gold badges155 silver badges180 bronze badges asked Nov 14, 2011 at 9:56 Daniel T.Daniel T. 38.4k37 gold badges144 silver badges207 bronze badges 2
  • 1 Can I ask what the final aim of this methodology is? – El Ronnoco Commented Nov 14, 2011 at 10:18
  • I'd like to be able to method chain it, for example $('ul.products').fadeIn().addProduct(data);. Also, it keeps it consistent with how other jQuery methods are called. – Daniel T. Commented Nov 14, 2011 at 16:59
Add a comment  | 

4 Answers 4

Reset to default 16

If you only want the addProduct and deleteProduct methods to feature on that single jQuery object, then what you've got will work fine; but you'll have to keep a reference to that jQuery object/ only use it once, to preserve the existance of the addProduct and deleteProduct methods.

However, these addProduct and deleteProduct methods are unique to that particular jQuery object; the methods won't exist on any other jQuery objects you create;

var productList = $.extend($('ul.products'), {
    addProduct: function(productData) {
        // add a new li item
    },
    deleteProduct: function(productId) {
        // delete li with id
    }
});

// Using this particular jQuery object (productList) will work fine.
productList.addProduct();
productList.removeProduct();

// However, addProduct() does not exist on new jQuery objects, even if they use
// the same selector.
$('ul.products').addProduct(); // error; [object Object] has no method 'addProduct'

The best way do to this would be to go-back-to-basics and define separate addProduct and deleteProduct functions, which accept a jQuery object. If you wanted to restrict these functions to they only worked on the ul.products selector, you could do;

function addProduct(obj) {
    obj = obj.filter('ul.products');

    // do something with `obj` (its a jQuery object)
}

This approach would be recommended as it keeps the jQuery.fn API consistent; otherwise you'd be adding addProduct and removeProduct to some jQuery.fn instances but not others, or making their usage redundant in others. With this approach however addProduct and removeProduct are always there, but don't get in anyones way if they don't want to use them.


Historical Notes

This answer was originally written in November 2011, when jQuery 1.7 was released. Since then the API has changed considerably. The answer above is relevant to the current 2.0.0 version of jQuery.

Prior to 1.9, a little used method called jQuery.sub used to exist, which is related to what you're trying to do (but won't help you unless you change your approach). This creates a new jQuery constructor, so you could do;

var newjQuery = jQuery.sub();
newjQuery.fn.addProduct = function () {
    // blah blah
};
newjQuery.fn.deleteProduct = function () {
    // blah blah
};

var foo = newjQuery('ul.products');
foo.deleteProduct();
foo.addProduct();

var bar = jQuery('ul.products');
bar.deleteProduct(); // error
bar.addProduct(); // error

Be careful though, the $ method alias would reference the old jQuery object, rather than the newjQuery instance.

jQuery.sub was removed from jQuery in 1.9. It is now available as a plugin.

You can make your own jQuery methods as follows:

$.fn.addProduct = function(){
  var myObject = $(this);
  // do something
}

// Call it like:
$("ul.products").addProduct();

This is a bit tricky though because you are making methods that are very specific to lists. So, to be sure you should at least add some checking on the object's type and handle the code correctly if the current object is, let's say an input element.

An alternative is to make a normal Javascript method that receives the list as a parameter. That way you can make a more list specific method.

I think you want to add a function to that DOM Object.

$(function(){
    // [0] gets the first object in array, which is your selected element, you can also use .get(0) in jQuery
    $("#test")[0].addProduct = function(info){
        alert("ID: " + this.id + " - Param: " + info);
    };


    $("#test")[0].addProduct("productid");
});

Above script wil alert "ID: test - Param: productid"

A live example: http://jsfiddle.net/jJ65A/1/

Or normal javascript

$(function(){
    document.getElementById("test").addProduct = function(info){
        alert(info);
    };
});

I think may be just using delegate in jQuery:

$(".parentclass").delegate("childclass","eventname",function(){});
发布评论

评论列表(0)

  1. 暂无评论