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();
});
});
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.
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);
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.
Just as an alternative, why not give those images another class which is the same for all, then your selector becomes much simpler, ie for a new class of myImgs
.
$('.myImgs').mouseleave(function() {
$(this).stop().fadeOut();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.