繁体   English   中英

jQuery代码在ajax加载的内容中不起作用

[英]jquery code doesn't work in ajax loaded content

是的,我在这里浏览了相同的文章,谷歌提供了帮助。 但是我是设计师,而不是编码员。 我可以复制\\粘贴一些代码,甚至可以更改某些内容,但是这个问题对我来说太难了。

因此,我的主页上有新闻,当您向下滚动时,下一页将加载ajax。 有一个脚本,可显示\\隐藏每个帖子的评分栏。 但是此代码在加载的内容中不起作用。 如果您不觉得困难,请修复它。

ps我曾尝试研究on()或live,但正如我之前难过的那样,不是我的水平。

$(document).ready(function() {

var element = $('#dle-content .main-news');
for (i=0; i<element.length; i++)
    {
        $(element[i]).addClass('news-'+i);
    }

$('#dle-content .main-news').hover(
    function() {
        $('.main-news-hidden').stop(true);
        $(this).find('.main-news-hidden').animate({
            'bottom':'0'
        },400
        );
    }, function() {
        $('.main-news-hidden').stop(true);
        $(this).find('.main-news-hidden').animate({
            'bottom':'-120'
        }, 0);
        $('.main-news-hidden').stop(true);
});

$('.top-news li').hover(
    function() {
        $('.top-news-hidden').stop(true).fadeOut(0);
        $(this).find('.top-news-hidden').animate({
            'opacity':'1'
        },400, function()
            {
                $(this).fadeIn();
            }
        );
    }, function() {
        $('.top-news-hidden').stop(true);
        $(this).find('.top-news-hidden').fadeOut(100);
});

var element2 = $('.top-news li');
for (i=0; i<element2.length; i++)
    {
        $(element2[i]).find('.list').append(i+1);
    }

});

尝试将代码包含在ajax html数据中,或者可以在附加html之后在完成功能中添加脚本。

$.ajax({
  url: "yourUrl",     
}).done(function(data) {
   $("#yourId").html(data);   // Solution 1 :  your content is loaded with ajax, Also this data has your jQuery script
   // Solution 2:  Now start you can call your script via function or add directly here (only html data is needed)
   yourFunction();
   //Solution 3: Now add your jquery code directly
   $(".someClass").click(function(){
     //events
   });
});

这是使用jQuery访问Ajax数据的三种不同方式。

我目前时间不多,但我会尽力而为。

当您的.hover()等被执行时,它们将绑定到您提供的实际元素上。 现在,当事件绑定到DOM元素时,通过AJAX加载的元素将不可用。

一种解决方案是已经提供的解决方案。 但是,恕我直言,这是一个更好的选择。 您需要的事件通常是“冒泡的”,这意味着它们沿DOM树向上传递了一些。 您需要将事件绑定到DOM元素,该元素不会通过AJAX进行替换/更改,而是持久的。 例如,如果您有一个容器#content ,您的AJAX被装入其中,则由于该冒泡,您希望将此容器作为事件绑定的基础。

尝试将$('.someClass').click()替换为

$('#content').on('click', '.someClass', function(event) {
  // your event handling
}); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM