【问题标题】:jQuery .on() not working with mousenter and mouseleavejQuery .on() 不适用于 mouseenter 和 mouseleave
【发布时间】:2013-06-16 12:27:31
【问题描述】:

我正在尝试使用.on(),因为.live() 已被弃用。但是我无法让.on() 工作。

我得到了这个 html 部分:

...
<div class="tile" data-position="0,0" style="top: 539.5px; left: 380px;">
    <div class="content">
        <div class="image"><img src="bla.png" alt="" /></div>
        <div class="title">title1</div>
    </div>
</div>

<div class="tile" data-position="0,1" style="top: 539.5px; left: 380px;">
    <div class="content">
        <div class="image"><img src="bla.png" alt="" /></div>
        <div class="title">title2</div>
    </div>
</div>

<div class="tile" data-position="0,2" style="top: 539.5px; left: 380px;">
    <div class="content">
        <div class="image"><img src="bla.png" alt="" /></div>
        <div class="title">title3</div>
    </div>
</div>
...

还有这个 jQuery:

$('.tile').on({
    mouseenter: function()
    {
        alert("enter");
        $(this).find('.content .image').animate({
            opacity: 0.5
        }, 100);
    },
    mouseleave: function()
    {
        alert("leave");
    }
});

无论我从 Jquery 的文档中使用什么语法,它都不起作用。 有谁知道这里出了什么问题?这种语法应该可以工作,它与 jQuery 的示例非常相似。

【问题讨论】:

  • 你还记得 document.ready 并首先包含 jQuery
  • 是的,我确实首先包含了 jQuery。但是你是说我必须把这个 jQuery 部分放在 document.ready() 中?我觉得有点奇怪
  • 所以它现在似乎确实有效。不太明白为什么它必须在 document.ready() 中。
  • 它在 jQuery 的文档中。您要么必须在 DOM 就绪处理程序中运行 javascript,要么在将元素添加到 DOM 之后运行 javascript,否则没有可使用的元素。
  • 猜猜有道理

标签: jquery mouseevent jquery-events jquery-on


【解决方案1】:

将它们放在&lt;body&gt; 底部的&lt;script&gt; 标记中。这将确保您附加这些处理程序的元素确实存在。

<script>
$('.tile').on({
    mouseenter: function()
    {
        alert("enter");
        $(this).find('.content .image').animate({
            opacity: 0.5
        }, 100);
    },
    mouseleave: function()
    {
        alert("leave");
    }
});
</script>
</body>

或者您可以使用 DOM ready 处理程序,它将在 DOM 完全加载且所有元素都可用后执行这些事件。

$(function() {
    $('.tile').on({
        mouseenter: function()
        {
            alert("enter");
            $(this).find('.content .image').animate({
                opacity: 0.5
            }, 100);
        },
        mouseleave: function()
        {
            alert("leave");
        }
    });
});

或者让无所不在的document 对象将事件委托给.tiles

$(document).on({
    mouseenter: function()
    {
        alert("enter");
        $(this).find('.content .image').animate({
            opacity: 0.5
        }, 100);
    },
    mouseleave: function()
    {
        alert("leave");
    }
},'.tile');

【讨论】:

    猜你喜欢
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多