-3
$(document).ready(function(){
    for(var i=0; i<7; i++){
       $("#id_"+i).hover(function(){ // i in this line is 1->7
             alert(i); // i in this line alway is 7 (I want i: 1-7 )
       });
    }
});

I use onmoveover and onmouseout in html to call function is not problem but i see it so long coding, anyone help me to solve this problem. Thankyou so much.

Viet Stars
  • 11
  • 2
  • _but i see it so long coding_ - Can you clarify what this means? – BSMP Jun 08 '15 at 03:52
  • I found a solution: $(document).ready(function(){ var func=[] for(var i=0; i<7; i++){ (function(u){ func[u] = function(){ alert(u); } })(i) $("#id_"+i).hover(func[i]); } }); // but i think func[u] had make many (i think 7th in end for) anyone help me to solve to shorter – Viet Stars Jun 08 '15 at 08:04

1 Answers1

0

Use this shorter alternative (the selector '[id^="id_"]' means "id that starts with id_"):

$('[id^="id_"]').hover(function () {
    alert(this.id.replace('id_', ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id_0">div 0</div>
<br>
<div id="id_1">div 1</div>
<br>
<div id="id_2">div 2</div>
<br>
<div id="id_3">div 3</div>
<br>
<div id="id_4">div 4</div>
<br>
<div id="id_5">div 5</div>
<br>
<div id="id_6">div 6</div>
<br>
omikes
  • 8,064
  • 8
  • 37
  • 50