How can I attach a method to a DOM element in jQuery?
Option #1:
// Store the element as an object:
var counterEl = $("#counter");
// Attach a method to the object:
counterEl.updateCount = function (value) {
// If the new value is greater than the existing value, update and animate the counter.
}
counterEl.updateCount(123); // Works.
$("#counter").updateCount(123); // Obviously does not work.
Option #2:
var counterEl = $("#counter");
// Store the function expression in .data():
counterEl.data('updateCount', function (value) {
// Major downside: If I access `this` here, it's the DOM window and not #counter.
}
counterEl.data('updateCount')(123); // Works.
$("#counter").data('updateCount')(123); // Works.
I understand why advice generally leans toward attaching a method to $.fn
so that it is reusa开发者_Python百科ble, but it isn't immediately obvious to me why attaching a unique method to an element is any worse than attaching a unique event handler (like .click()
) to an element.
Is there a better way to attach a method to a DOM element in jQuery? The .data()
approach would be great if I could access the element through this
.
How can I attach a method to a DOM element in jQuery?
There are several ways of doing this, one way is using jQuery.data
as you already propose yourself. Another way is to add a function as a method directly on the object. Many people consider this DOM pollution though, but really, this is what libraries like jQuery does all the time, so if you need it, do it, just think of the consequences first, and make sure you don't break stuff in the process ;)
Should I even be doing that?
That depends what you need, there is nothing wrong with it in itself, but it breaks several design patterns you may want to follow.
Any reason not to store a function expression in .data()?
Not really, jQuery does this internally all the time.
Putting a function in data can for example be done like this:
$('#SomeId').data('func', function() { alert('Hello world!'); });
And called like this:
$('#SomeId').data('func')();
There is nothing stopping you from doing this, but it does have a little bit of code smell to id. You should consider if this is really the best solution.
An alternative could be to store an object in the data, which can have methods. Example:
var info = {
message: 'Hello world!';
show: function() { alert(this.message); };
};
$('#SomeId').data('info', info);
Called like this:
$('#SomeId').data(info').show();
Simply...
$("p").click(function(){
// do something
});
...where "p"
could be any CSS3-like selector. Examples:
.classname
#someID
精彩评论