I want to s开发者_运维知识库elect all images on my page and attach a function to the mouseover event. Here is a jsFiddle showing you what I have so far. At the bottom of the JavaScript section, you can see that I am running the same code twice, once for each image. It seems to me that I should be able to use the .each() function here, but I've tried to do it and can't get it to work. Here are the two duplicate calls I want to turn into one:
$("#gen").one('mouseover', function() { runTransfer('gen'); return false; });
$("#bo").one('mouseover', function() { runTransfer('bo'); return false; });
FYI, there is also a bug here (different part of the code) that I'm trying to solve...but only one question at a time. :)
To answer your question literally, you can just use the multiple selector:
$("#gen, #bo").one('mouseover', function() {
runTransfer(this.id);
return false;
});
Can you give the images a class and then select on the class?
HTML:
<img class="addEventToMe" src="..." alt="..."/>
jQuery:
$(".addEventToMe").each(function(elm) {
elm.one('mouseover', function() { runTransfer('gen'); return false; });
}
Here is some code to do the trick:
$.each(['gen','bo'],function(i,id){$('#'+id).one('mouseover',function(){
runTransfer(id);
})})
精彩评论