Reputation: 2057
I am curious why this does not work. This is more hypothetical but I did run into this issue on a site that I am doing. I am trying to avoid a jQuery function inside a function. The this selector is the window instead of each of the boxes.
EDIT*** I DO UNDERSTAND HOW to do this doing the $(".box").each(function(){ // code here }); but is it not sloppy or bad practice functions inside of functions?
CSS
.box {
height: 50px;
width: 50px;
background: green;
margin-bottom: 5px;
}
HTML
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
Javascript
function changeMe(obj) {
console.log(obj);
$(obj).css("background", "blue");
}
$.each($(".box"), changeMe(this));
Upvotes: 0
Views: 6998
Reputation: 1959
Second each paramater must be function - not function result:
$(".box").each(changeMe);
function changeMe(n, obj) { ........
Upvotes: 4
Reputation: 53301
When you call the $.each
function,this
still refers to the window object, as you noted. To have this
refer to the jQuery object, you could call it in an anonymous function, which gets the proper scope applied.
$(".box").each(function(){
changeMe(this);
});
As a sidenote, it is absolutely not bad practice, sloppy, or anything negative whatsoever to call functions inside of other functions in Javascript. In fact, it's a cornerstone of Javascript programming (one of its most important concepts, callbacks, relies on functions inside of other functions). Functions are first-class citizens in Javascript, so they can be passed around, stuck inside other functions, and treated as any other object would be.
You may be interested in reading more about functions in the MDN documentation. They explain a lot about functions being objects, nesting functions, closures and more, which may interest you if you wish to understand how functions are best used.
Upvotes: 4
Reputation: 22817
Because the second parameter of $.each
should be a function
.
If you pass changeMe(this)
, you are passing the return value of changeMe
- you should wrap it into an anonymous function:
$.each($(".box"), function(){
changeMe(this)
});
Upvotes: 2