jQuery onmouseover在第二个事件上触发 [英] Jquery onmouseover triggers on second event

查看:152
本文介绍了jQuery onmouseover在第二个事件上触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Jquery中创建了以下函数

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?

非常感谢!

推荐答案

问题是,只有将鼠标悬停在元素上并且触发了内联onmouseover之后,您才使用jQuery绑定事件.

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.

由于看起来onmouseover事件对于您的应用程序结构至关重要,因此请将您的JavaScript更改为以下内容:

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");
}

理想情况下,我会使用data-属性:

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");
    });
});

这篇关于jQuery onmouseover在第二个事件上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆