i have 3 divs with the same class.
<div id="qq1" class="cl">sentence</div>
<div id="qq2" class="cl">sentence</div>
<div id="qq3" class="cl">sentence</div>
well i’d like to know how can i write correct code for entering mouse calling with one function for 3 divs (calling cl class) and returning the correct id for change css.for ex:
<script>
$('.cl').live('mouseenter', function() {
var currentId = $(this).attr('id');
$('currentId').css("background-color", "#99cc33");
$('currentId').css("color", "white");
});
$('.cl').live('mouseleave', function() {
var currentId = $(this).attr('id');
$('currentId').css("background-color", "white");
$('currentId').css("color", "#404040");
});
</script>
But there’s something wrong ’cause it doesn’t work
You don’t ever use the
currentIdvariable, instead you try to use a string that contains the letters c, u, r, etc.,'currentId'.To make it work with that variable you would need to say
$('#' + currentId).css()– so if, e.g.,currentIdis'qq1'then in effect you would be saying$('#qq1').css().However you don’t need the id at all because you can simply use
$(this):Within a jQuery event handler
thisrefers to the DOM element itself, while$(this)creates a jQuery object for that element so that you can call jQuery methods on it. Note that the.css()method accepts a map of multiple properties so you can set them all with a single call – I’ve shown that syntax in themouseenterbut not themouseleaveso that you can compare.(Note: not related at all to your question, but if you are using jQuery 1.7+ you should stop using
.live()because it has been deprecated in favour of.on()– there are instructions on the.live()doco page for how to convert your code. If you are using < 1.7 but > 1.4.2 you should use.delegate().)