jQuery列表中每个产品的基于悬浮的弹出事件

时间:2013-08-01 08:21:17

标签: javascript jquery asp.net-mvc-4

我对jquery中的函数有一点问题。每次用户悬停产品时,我都需要显示弹出窗口。我的产品在列表中,我想为每个产品指定一个弹出窗口,以显示它的标题和描述:

这是产品列表(以缩略图显示)

 <!-- This Div contains the List of Products -->
<ul class="thumbnails">

                @foreach (var thumbnail in Model.ForfaitsInThumbNail)
                {
    <div class="thumbnail">
                                <img src= "@Url.Action("GetById", "ImageForfait", new { idForfait = thumbnail.Forfait.Id })" alt=""/>
                                <div class="caption">
                                    <h2 class="fontTitle">@thumbnail.Forfait.Titre</h2> <h5 class="fontYearHijri"> pour l'année @thumbnail.Forfait.AnneeHijri H </h5>

                                    .......
                                </div>
       <!-- This div should contain the pop-up for every Product -->
                            <div class='pop-up' id='pop-up'>    <h3>"@thumbnail.Forfait.Titre"</h3><p>"@thumbnail.Forfait.Description"</p></div>
                            </div>
    </div>
                   }
</ul>

这是我糟糕的 jquery功能,它只适用于一个产品,而不是所有产品都在列表中

<script>
$('.thumbnail').each(function() {
    $(this).hover(function (e) {
    $('.pop-up').show()
        .css('top', e.pageY + 20)
        .css('left', e.pageX + 10)
        .appendTo('body');
}, function () {
    $('.pop-up').hide();
});
});
$('.thumbnail').each(function() {
    $('.thumbnail').mousemove(function(e) {
        $(".pop-up").css('top', e.pageY + 20).css('left', e.pageX + 10);
    });
});

此函数没有错误,但它只显示最后一个产品的弹出窗口,这似乎是逻辑,因为它无法识别指定产品的div。所以我的问题是,如何实现我想要的功能(每个产品的特殊弹出窗口)?有任何想法吗 ?谢谢:)

2 个答案:

答案 0 :(得分:1)

I've update this answer by constructing a fiddle to show a working solution。将来,请你尽可能提供一个小提琴,因为它为我们自己构建一个节省了很多时间。

这是我的JavaScript:

// Note, this is important
$(document).ready(function () {    

    // We don't need an each, and include the e event handler
    $('.thumbnail').hover(function (e) {
        $('#pop-up').show()
            .css('top', e.pageY + 20)
            .css('left', e.pageX + 10)
            .appendTo('body');
    }, function () {
        $('#pop-up').hide();
    });
    $('.thumbnail').mousemove(function (e) {
        $("#pop-up").css('top', e.pageY + 20).css('left', e.pageX + 10);
    });
});

您应该注意的事项:您不需要在同一元素上同时拥有ID #pop-up和类.popup,除非这是一个继承自标准的特殊弹出窗口弹出类。看起来您的ID / Class使用率可能已关闭,因此只要确保您在某些内容是唯一的时使用ID,并在有多个实例时使用类。

我做了几个修复:

  • 始终将jQuery包装在$(document).ready()方法中,这将确保在应用事件之前完全加载DOM
  • 您忘记在hover函数中添加事件处理程序,但我认为您已更新了包含此问题的问题。

答案 1 :(得分:0)

您忘记在悬停事件

上传递事件对象参数
//do this 
...
$(this).hover(e){
  --
}
...

希望这应该有用。

如果您注意到您使用了(e.pageX)那么(e)来自哪里。它必须作为参数传递。