开发者

jquery loop hover button

ok i have 6 buttons, im trying to have a jquery listener for w开发者_Go百科hen you hover over one of the 6 buttons, it changes class. im using a for loop to do this, heres my code:

$(document).ready(function() {
for($i=1;$i<7;$i++) {
      $('#button'+i).hover(function() {
        $(this).addClass('hovering');
      }, function() {
        $(this).removeClass('normal');
      });
}  
});

each button has an id of "buttonx" ( the x being a number )

help?


You don't need to loop over a bunch of generated IDs. You can simply give each of them the class 'normal' and:

$("button.normal").hover(function() {
    $(this).addClass("hovering");
}, function() {
    $(this).removeClass("hovering");
});

'button.normal' will return a collection of all buttons with the 'normal' class, so there's no need for a loop, the hover event will be applied to every element in the collection.


You shouldn't need to use a loop. Just use the attribute startsWith selector on the id. Also you may want to change how you apply/remove the classes to make sure that no class has both normal and hovering.

$('[id^=button]').hover( function() {
     $('[id^=button]').removeClass('hovering');
     $(this).addClass('hovering').removeClass('normal');
},
function() {
     $(this).removeClass('hovering').addClass('normal');
});


Note that karim79's answer is a good way to go.

In your code, you are declaring the loop counter as '$i' but trying to reference 'i'. It should be $('#button'+$i)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜