动态添加的javascript未运行

时间:2016-07-02 21:12:20

标签: javascript ajax

我正在构建一个主要基于ajax构建的网站。我的一些JS作为我通过ajax加载的页面的一部分。无法从之前加载的其他JS脚本调用JS中的函数。正如我所理解的那样,它必须在代码中没有真正声明,并且我可以在代码上使用eval()。但这感觉就像浪费资源一样,因为代码运行起来并且不需要使用已经声明的代码。

我的小ajax页面加载器。

$(document).ready(function(){
    var old = "home"
    $("#topMenu a").on("click",function(){
        if(typeof edit_menu !== 'undefined' && edit_menu){
            return;
        }
        var link = $(this).attr("data-link");
        //Load Ajax
        LoadPage(link, old);
    });
});

function LoadPage(link, old){
    $.ajax({
        url: "pages/" + link + ".php",
    }).done(function(data){
        $("#content").html(data);
    });
    Hide();
    history.pushState(old,null,"?page=" + link);
}

如果我以管理员身份登录,那么我还会将一个admin JS文件作为DOM的一部分加载。该脚本调用另一个动态加载的JS文件中的函数。该函数不运行,因为admin JS文件不知道新的函数。

动态添加的JS文件是其他HTML代码的脚本标记的一部分。 动态添加代码的示例。

    <script src="/javascript/projects.js"></script>
    <header>Projects</header>

<article>
    <h1>First project</h1>
    <section class="summary">
Lorem ipsum is da shit
    </section>
    <section class="text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam orci, hendrerit a justo sit amet, egestas ullamcorper orci. Aliquam quis facilisis urna. Fusce blandit pellentesque elit. Vivamus ullamcorper luctus felis in rutrum. Nam quis facilisis mauris. Nunc iaculis sagittis sollicitudin. Ut imperdiet, purus et fermentum tempor, leo mauris feugiat libero, eu pulvinar odio felis sed tortor. Mauris vel libero orci. Suspendisse a mollis turpis. Maecenas egestas felis eget ultrices porta. Nulla non metus ut augue faucibus ultrices. Phasellus arcu magna, vulputate eget sollicitudin a, ullamcorper a ipsum. Suspendisse potenti. Pellentesque eget vulputate ipsum.</p>             <p>Ut ultricies faucibus sapien, ut sodales turpis rhoncus molestie. Vivamus luctus auctor pellentesque. Phasellus ut ex vulputate, congue felis nec, pharetra odio. Ut ligula ante, luctus nec enim ac, lobortis ultrices elit. Quisque sed justo a nibh congue tempor sit amet ut mauris. In non enim nulla. Nulla et dolor sollicitudin, finibus ante eu, egestas purus. Phasellus sit amet eros dignissim, pellentesque elit tempor, sagittis eros. Donec sollicitudin velit ipsum, semper ultrices sapien blandit non. Phasellus vehicula orci in ipsum blandit hendrerit. Vestibulum facilisis dolor ac tincidunt fermentum.</p>
    </section>
    <span>Update text</span> <input type="checkbox" class="update_projects" data-id="First project" /><br /><button class="update_text">Update</button><input type="hidden" class="token" value="4926dd431992894a8364ca4d89733038be0cb0ec4897eb2a417637685554b6df40149522a858b5bfaaa91526b84718cdd54b301229371841dc2f022bbd0f804eaf31abb51caef55b26cca3209cc3b0838f194176f78f0931b2217669cd2912faa25a3c3e469ce686d79ac7a7852fbfee9d6d4dc5da18b499e703b4ef57fc88c1a99ccf8943af5853433f911ce276ff13e9ecbfb074d747f1a07f26c141f80383a149902dfe7469262724e2f67aae48d9919d486855a892b17681660ab3e0d25f98e714c3d98cc903" /><input type="hidden" class="id" value="1" /><br /><input type="text" name="tag" class="tag" value="php" />
</article><article>
    <h1>Secons project</h1>
    <section class="summary">
And I'm not lying
    </section>
    <section class="text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam orci, hendrerit a justo sit amet, egestas ullamcorper orci. Aliquam quis facilisis urna. Fusce blandit pellentesque elit. Vivamus ullamcorper luctus felis in rutrum. Nam quis facilisis mauris. Nunc iaculis sagittis sollicitudin. Ut imperdiet, purus et fermentum tempor, leo mauris feugiat libero, eu pulvinar odio felis sed tortor. Mauris vel libero orci. Suspendisse a mollis turpis. Maecenas egestas felis eget ultrices porta. Nulla non metus ut augue faucibus ultrices. Phasellus arcu magna, vulputate eget sollicitudin a, ullamcorper a ipsum. Suspendisse potenti. Pellentesque eget vulputate ipsum.</p>
            <p>Ut ultricies faucibus sapien, ut sodales turpis rhoncus molestie. Vivamus luctus auctor pellentesque. Phasellus ut ex vulputate, congue felis nec, pharetra odio. Ut ligula ante, luctus nec enim ac, lobortis ultrices elit. Quisque sed justo a nibh congue tempor sit amet ut mauris. In non enim nulla. Nulla et dolor sollicitudin, finibus ante eu, egestas purus. Phasellus sit amet eros dignissim, pellentesque elit tempor, sagittis eros. Donec sollicitudin velit ipsum, semper ultrices sapien blandit non. Phasellus vehicula orci in ipsum blandit hendrerit. Vestibulum facilisis dolor ac tincidunt fermentum.</p>
    </section>
    <span>Update text</span> <input type="checkbox" class="update_projects" data-id="Secons project" /><br /><button class="update_text">Update</button><input type="hidden" class="token" value="4926dd431992894a8364ca4d89733038be0cb0ec4897eb2a417637685554b6df40149522a858b5bfaaa91526b84718cdd54b301229371841dc2f022bbd0f804eaf31abb51caef55b26cca3209cc3b0838f194176f78f0931b2217669cd2912faa25a3c3e469ce686d79ac7a7852fbfee9d6d4dc5da18b499e703b4ef57fc88c1a99ccf8943af5853433f911ce276ff13e9ecbfb074d747f1a07f26c141f80383a149902dfe7469262724e2f67aae48d9919d486855a892b17681660ab3e0d25f98e714c3d98cc903" /><input type="hidden" class="id" value="2" /><br /><input type="text" name="tag" class="tag" value="" />
</article></section>

更新 经过一些测试后,我发现JS无法找到我添加的任何HTML,而同时添加的js可以。

3 个答案:

答案 0 :(得分:1)

我正在尝试来理解这个问题,但由于我暂时无法评论其部分内容并不清楚,我使用 jsfiddle 它可以帮助,是否有可能制作一个小例子而不是所有的代码来帮助我理解正在发生的事情。从...开始 这个函数例如:

function LoadPage(link, old){
    $.ajax({
        url: "pages/" + link + ".php",
    }).done(function(data){
        $("#content").html(data);
    });
    Hide();
    history.pushState(old,null,"?page=" + link);
}

https://jsfiddle.net/3z62n8c2/

答案 1 :(得分:0)

要加载脚本,您必须将其作为HTML元素附加,如下所示:

}).done(function(data) {
    var el = $(document.createElement('div')).html(data);
    var scripts = el.find('script');

    for(var i = 0; i < scripts.length; i++) {
        window.eval(scripts[i].innerHTML);
        scripts[i].remove();
    }

    $('#content').html(el.html());
});

答案 2 :(得分:0)

尝试使用以下脚本,这将从加载的HTML中删除脚本,并在添加内容之前将其加载到页面上。此外,它确保相同的JavaScript文件不会多次添加。

function LoadPage(link, old){
    $.ajax({
        url: "pages/" + link + ".php",
    }).done(function(data){
        $loadedData = $("<div>"+data+"</div>");
        $loadedData.find('script[src]').each(function(i,v){
            var jsPath = $(this).attr('src');
            if($('[src="'+jsPath+'"]').length == 0){
               var tag = document.createElement('script');
               tag.src = jsPath;
               var firstScriptTag = document.getElementsByTagName('script')[0];
               firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
            }
        });
        $loadedData.find('script[src]').remove(); 
        $("#content").html($loadedData.html());
    });
    Hide();
    history.pushState(old,null,"?page=" + link);
}