0

我正在开发一个使用 AJAX 显示文章的 wordpress 网站。我在成功回调中添加了一些 jquery 代码。我的需求之一是在鼠标悬停时显示图像。除了鼠标悬停效果外,我所有的代码都有效。

所以这是我的 ajax 函数:

function loadArticle(pageNumber, loop, term){    
    $.ajax({
        url: ajax_var.url,
        type:'POST',
        data: someData, 
        success: function(html){
            // This will be the div where our content will be loaded
            $("#content").append(html);    

            // Zoom box
            $('img.static').hide();
            $(".ad-preview").live({
                mouseover: function() {
                    $(this).find('img.static').stop().fadeIn();
                },
                mouseout: function() {
                    $(this).find('img.static').stop().fadeOut();
                }
            });

            //  Other stuff...
        });

        return false;
    }

});

和 HTML:

<div class="ad-preview">
    <a target="_blank" href="">
        <img src="img/zoom.png" /></a>            
    </a>
</div>

实现这种效果的好方法是什么?

4

2 回答 2

2

首先,您可能应该使用on而不是live. 其次,委托处理程序不必在回调中应用。因为它们被委派给保留在页面上的更高级别的元素,所以您可以在页面加载时应用它们。

    $("body").on('mouseover', '.ad-preview', function() {
            $(this).find('img.static').stop().fadeIn();
    })
    .on('mouseout', '.ad-preview', function() {
            $(this).find('img.static').stop().fadeOut();
    });
于 2013-01-24T00:12:28.740 回答
2

.live 是一个活跃的监听器,被.on取代

您可以将它放在 ajax 调用之外,在 js 的基础级别 - 换句话说,不是在 document.ready 调用或其他函数中。它将适用于通过 ajax 加载的 dom 元素。

于 2013-01-24T00:11:43.647 回答