Reputation: 11733
I'm new to jQuery so please advice me if I'm going in the wrong direction.
I have a function that takes as argument a "jQuery object", like this:
function protectImageFromRightClick(image_object) {
// yeah ok i know this is only a dumb protection!!
image_object.bind('contextmenu', function(e) {
return false;
});
image_object.mousedown(function(){
return false; // for prevent drag
});
}
and I want to call it on selection. I've tried to call it with each()
:
$( ".photo" ).each(function (i) {
protect(this);
});
But this
seems to refer to a DOM object that doesn't have any .bind()
method.. I don't understand very well how I can resolve this.. any ideas?
The face is that I'm using that funciton somewhere else in the code so a solution like:
$('some selection').bind()
is not a good solution because in this way i'd write only code repetition..
Upvotes: 1
Views: 175
Reputation: 2606
if you iterate with each, then every iteration, the callback is called, the argument (i) is your element.
Like in
java:
Vector<Integer> photo = new Vector<>();
photo.add(2); //ok very constructed..
for(int v:photo){
// here v is your iteration variable
}
JS:
$( ".photo" ).each(function (k,v) {
protect(v);
});
However, v is now pure js, not jQuery, so you might use:
$( ".photo" ).each(function (k,v) {
protect($(v));
});
If you wonder what k is here: k stands for key, v for value.
In an array, this might be simple, k is 0,1,2,...
but this also works on objects like {"k1":"v1","k2":"v2"}
Upvotes: 1
Reputation: 82267
When you call the jQuery function with a selector it does a couple tasks. First, it constructs the jQuery object. Then, it attaches the jQuery API to the newly constructed object. Then, it constructs an array of DOM elements matching the selector.
When you use each
on a jQuery object, or when you are inside of a callback closure, the this
keyword is going to refer to the current DOM Element that jQuery is working on.
In short,
$( ".photo" ).each(function (i) {
//this == the current element with class="photo"
//$(this) == a jquery object instanced with an
// array of elements containing only the
// current element with class="photo" that
// each is working with
});
Upvotes: 2
Reputation: 12402
The .each
method sets this
to the actual DOM object, you can turn that DOM object into a jQuery object by wrapping it with another $()
$(".photo").each(function () {
protect($(this));
});
Upvotes: 0
Reputation: 164739
You could always check for a jQuery object in your function and cast it if necessary, eg
if (!image_object instanceof $) {
image_object = $(image_object);
}
Upvotes: 0