JQuery onmouseover fires a second event

I created the following function in jQuery

function menuItem(x,i) { var imgALT = $(x).text(); $(x).mouseover(function() { $(x).parent().parent().parent().children("img").attr("src", "menu/menu"+i+".jpg"); $(x).parent().parent().parent().children("img").attr("alt", imgALT); $(x).parent().children("span").css("color", "#FFFFFF"); $(x).css("color", "#CA0109"); }); }; 

And I run it using the following:

 <span onmouseover="menuItem(this,'09-01')">ๆœˆไบฎ่ฆ้ค… (2ไปฝ)</span> 

It works exactly as I intend it, but only after I pause a second time, not the first. I assume this is possibly a download problem? How should I ensure that it works when the mouse first appears, as well as in subsequent events?

Thank you very much!

0
source share
2 answers

The problem is that you bind the event using jQuery only after you hover an element on it, and the built-in onmouseover fired.

Since it looks like the onmouseover event is critical to your application structure, change your JavaScript to something like this:

 function menuItem(x,i) { var $x = $(x); var imgALT = $x.text(); $x.parent().parent().parent().children("img").attr("src", "menu/menu"+i+".jpg"); $x.parent().parent().parent().children("img").attr("alt", imgALT); $x.parent().children("span").css("color", "#FFFFFF"); $x.css("color", "#CA0109"); } 

Ideally, I would use data- attributes:

HTML

 <span data-image="09-01">ๆœˆไบฎ่ฆ้ค… (2ไปฝ)</span> 

Javascript

 $(document).ready(function() { $('span[data-image]').mouseover(function() { var $this = $(this); var $images = $this.parent().parent().parent().children("img"); $images.attr("src", "menu/menu" + $this.data('image') + ".jpg"); $images.attr("alt", $this.text()); $this.siblings("span").css("color", "#FFFFFF"); $this.css("color", "#CA0109"); }); }); 
+3
source

Use document.ready function

 $(document).ready(function(){ $('span').mouseover(function(){}); }); 
+1
source

Source: https://habr.com/ru/post/1487785/


All Articles