javascript 如何将函数添加到某些 jQuery 对象,而不是其他对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8119851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add functions to some jQuery objects, but not others?
提问by Daniel T.
Let's say I have a <ul>
list:
假设我有一个<ul>
列表:
<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:
我想用 jQuery 选择它,然后向该对象添加一些函数。例如,我想添加一个addProduct(productData)
函数和一个deleteProduct(productId)
函数。但是,我希望这些函数只添加到选择器返回的对象中。例如,这样的事情:
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.
我将如何使用 jQuery 做到这一点?这里的关键是我只想将函数添加到 jQuery 选择器返回的实例中。换句话说,我不想修改 jQuery 的原型或创建插件,因为这些将使函数在所有内容中可用,而我只想将函数添加到一个特定实例。
采纳答案by Matt
If you only want the addProduct
and deleteProduct
methods to feature on that singlejQuery 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.
如果您只想在单个jQuery 对象上使用addProduct
和deleteProduct
方法,那么您所拥有的就可以正常工作;但是您必须保留对该 jQuery 对象的引用/只使用它一次,以保留和方法的存在。addProduct
deleteProduct
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;
但是,这些addProduct
和deleteProduct
方法对于特定的 jQuery 对象来说是独一无二的;您创建的任何其他 jQuery 对象上都不存在这些方法;
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;
最好的方法是回归基础并定义单独的addProduct
和deleteProduct
函数,它们接受一个 jQuery 对象。如果您想将这些功能限制为仅适用于ul.products
选择器,您可以这样做;
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 somejQuery.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.
推荐使用这种方法,因为它可以保持jQuery.fn
API 的一致性;否则你会被添加addProduct
,并removeProduct
以一些jQuery.fn
实例,但不是别人,或使它们的使用冗余别人。但是addProduct
,使用这种方法并且removeProduct
始终存在,但是如果他们不想使用它们,请不要妨碍他们。
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 current2.0.0 version of jQuery.
这个答案最初写于 2011 年 11 月,当时 jQuery 1.7 发布。从那时起,API 发生了很大变化。上面的答案与当前2.0.0 版本的 jQuery 相关。
Prior to 1.9, a little used method called jQuery.sub
used to exist, which is relatedto 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;
在 1.9 之前,jQuery.sub
曾经存在过一个叫做曾经使用过的很少使用的方法,这与您要执行的操作有关(但除非您改变方法,否则不会帮助您)。这将创建一个新的 jQuery 构造函数,因此您可以这样做;
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
对象,而不是newjQuery
实例。
jQuery.sub
was removed from jQuery in 1.9. It is now available as a plugin.
jQuery.sub
在 1.9 中从 jQuery 中删除。它现在可以作为插件使用。
回答by Bas Slagter
You can make your own jQuery methods as follows:
您可以创建自己的 jQuery 方法,如下所示:
$.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.
另一种方法是制作一个普通的 Javascript 方法,该方法接收列表作为参数。这样你就可以制定一个更具体的方法。
回答by Niels
I think you want to add a function to that DOM Object.
我认为您想向该 DOM 对象添加一个函数。
$(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"
上面的脚本会提示“ID:test - Param:productid”
A live example: http://jsfiddle.net/jJ65A/1/
一个活生生的例子:http: //jsfiddle.net/jJ65A/1/
Or normal javascript
或者普通的javascript
$(function(){
document.getElementById("test").addProduct = function(info){
alert(info);
};
});
回答by gacon
I think may be just using delegate in jQuery:
我认为可能只是在 jQuery 中使用委托:
$(".parentclass").delegate("childclass","eventname",function(){});