0

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!

4

2 回答 2

3

问题是您仅在将鼠标悬停在元素上并且内联onmouseover已触发后才使用 jQuery 绑定事件。

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

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-属性:

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");
    });
});
于 2012-10-05T07:08:09.560 回答
1

使用document.ready函数

$(document).ready(function(){
  $('span').mouseover(function(){});
    });
于 2012-10-05T07:16:54.457 回答