Jquery onmouseover triggers on second event

送分小仙女□ 提交于 2019-12-11 14:11:39

问题


I've 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 trigger it using the following:

<span onmouseover="menuItem(this,'09-01')">月亮蝦餅 (2份)</span>

It works exactly as I intend it to, but only after I mouseover the span for the second time, not the first. I assume this is perhaps a loading issue of some kind? How should I go about ensuring it triggers on the first mouseover, as well as subsequent events?

Many thanks!


回答1:


The problem is that you're binding the event using jQuery only after you've hovered over the element and the inline onmouseover has fired.

Since it looks like that onmouseover event is critical to your application's 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");
    });
});



回答2:


Use document.ready function

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


来源:https://stackoverflow.com/questions/12741209/jquery-onmouseover-triggers-on-second-event

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