to attach an event to each element of an array

£可爱£侵袭症+ 提交于 2021-01-28 04:03:06

问题


I have made several icon, and on their mouse hover they should do something. Now, I have made an array of my Icons, but as I apply each() to the set, it does not work:

So i need the following block of code to attach a hover event to each element of the set.

var icon_set = new Array('.icon-online', '.icon-save', '.icon-sms',
    '.icon-access', '.icon-support');
icon_set.each(function () {
    $(this).mouseleave(function () {
        img.stop().fadeOut();
    });
});

回答1:


Try Array.join()

var icon_set = new Array('.icon-online', '.icon-save', '.icon-sms',
    '.icon-access', '.icon-support');
$(icon_set.join()).mouseleave(function () {
    img.stop().fadeOut();
});


icon_set.each(function () { --> .each() doesn't work with array

Use jQuery.each() , array.forEach(callback[, thisArg]) for array.




回答2:


icon_set is a raw JavaScript Array. It doesn't have an each method. Use Array.prototype.forEach or $.each and wrap each array element with $();

icon_set.forEach(function (el) {
    $(el).mouseleave(function () {
        $(this).stop().fadeOut();
    });
});

or

$.each(icon_set, function(index, el) {
  $(el).mouseleave(function () {
    $(this).stop().fadeOut();
  });
});

And prefer using the array literal syntax([]) over the Array constructor

['.icon-online', '.icon-save', 
 '.icon-sms','.icon-access', '.icon-support'].forEach(yourMouseleaveHandler);



回答3:


If all your icons have a classname that begin with icon- you can use this Jquery Starts With Selector

$('*[className^="icon-"]').mouseleave(function() {
    // Do something
});

PS: It will select all icons which begin with icon-. It depends, you may/may not want that.




回答4:


Just as an alternative, why not give those images another class which is the same for all, then your selector becomes much simpler, i.e for a new class of myImgs.

$('.myImgs').mouseleave(function() {
     $(this).stop().fadeOut();
});


来源:https://stackoverflow.com/questions/20284556/to-attach-an-event-to-each-element-of-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!