加载内容和javascript异步问题

时间:2015-05-20 21:31:20

标签: javascript jquery html ajax

我将index.htm中的内容替换为project.htm中的内容。单击#front时,它会在project.htm上链接,并动态加载(替换)新内容。但我有一个问题,如何执行我正在加载新内容的JavaScript。要加载脚本,我使用了函数 getScript 。这是我用来加载新内容和脚本的函数:

$(document).ready(function() {
$('a#front').click(function() { 
    var toLoad = $(this).attr('href')+' #content';
    $('#content').hide("drop", { direction: "left" }, "slow", loadContent);
    window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
    function loadContent() {
        $('#content').load(toLoad ,'',showNewContent())
    }
    function showNewContent() {
        $('#content').show("drop", { direction: "right" }, "slow");
        $.getScript('js/project.js');
    }
    return false; 
});

}); 我加载新内容时加载的Javascript只有在顶部或此处有警报时才有效。但是,当我尝试加载更复杂的内容(仅仅是文本,我把div,标题等),它不起作用:     

$.ajax({
    success: function(data) {
        $('a#link').click(function() { 
            $("p").css("color","white");
        });
    }
});

你能帮我解决这个问题,或者你有不同的解决方案吗?

1 个答案:

答案 0 :(得分:0)

我解决了这个问题并且为了从新文件和javascript中加载内容而加载了内容。请注意,在新文件中,我需要将内容包装到ID为 content 的div中,然后将其加载到本机文档中的div中,并使用相同的名称 - content 。 以下是我如何使用 getScript 函数加载新内容以及如何调用新的javascript文件:

$('a#front').click(function() { 
        var toLoad = $(this).attr('href')+' #content';
        $('#content').hide("drop", { direction: "left" }, "slow", loadContent);
        window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
        function loadContent() {
            $('#content').load(toLoad ,'',showNewContent())
        }
        function showNewContent() {
            $('#content').show("drop", { direction: "right" }, "slow");
            $.getScript('js/project.js');
            $.getScript('js/section.js');
            $.getScript('js/carousel.js');
        }
        return false; 
    });

为了强制加载javascript执行,我使用了 setTimeout 函数。例如,这是在carousel.js文件中查找激活轮播的代码:

$(document).ready(function($) {
    setTimeout(function(){ 
        //run carousel
        $("#owl-example").owlCarousel();    
    }, 100);    });

如何运作,您可以看到here