Reputation: 275
I move some code from hover function to outside be hover_in()
.
$(this)
in function hover_in()
it doesn't work, how to fix it?
How should I replace $('this')
to make it work?
$('.a').hover(function(){
hover_in();
// var hover_id = $(this).attr('id');
}, function(){});
function hover_in(){
var hover_id = $(this).attr('id'); // not work
};
<div class='a' id="a1"></div>
<div class='a' id="a2"></div>
<div class='a' id="a3"></div>
...
Upvotes: 0
Views: 156
Reputation: 339947
If you "unwrap" the call to your function it'll work fine:
$('.a').hover(hover_in, function() {});
The reason is that jQuery will set this
when it calls the given handler, but in your original version you don't do anything to ensure that its value is passed on to your hover_in
function when you call it.
If you don't want the event handler to do anything else then there's no advantage in wrapping the whole thing in an anonymous function - quite the opposite, as you've found.
If you want additional stuff to be done in the handler, you could do this:
$('.a').hover(function(ev) {
hover_in.call(this, ev); // omit 'ev' if it's not needed
...
}, ...);
which explicitly calls hover_in
with the right this
value.
Note also that $(this).attr('id') === this.id
- the latter is simpler and far more efficient.
Also, if you don't want to pass the second parameter to .hover
, just use .mousenter
instead. Better yet:
$('.a').on('mouseenter', hover_in);
function hover_in(){
var hover_id = this.id;
...
};
Upvotes: 4
Reputation: 2604
Please have a look at http://jsfiddle.net/2dJAN/55/
$(document).ready(function(){
$('.a').hover(function(){
//var hover_id = $(this).attr('id');
// alert(hover_id);
hover_in($(this));
});
function hover_in(div){
var hover_id = div.attr('id');
alert(hover_id);
}
});
Upvotes: 0
Reputation: 52006
Pass the value as an argument :
$('.a').hover(function(){
var hover_id = $(this).attr('id');
hover_in(hover_id);
}, function(){});
function hover_in(id){
//use id here
};
Upvotes: 0
Reputation: 255015
You have 2 options:
pass this
as an argument to hover_in
:
the call would look like: hover_in(this);
the function definition would look like:
function hover_in(that) {
var hover_id = $(that).attr('id'); // not work
};
To invoke it in a way like hover_in.call(this);
Upvotes: 3