对 JQuery .load() 的 JavaScript 函数调用的行为与预期不符

标签 javascript php jquery

我正在学校网站上工作,目前正在实现某种管理仪表板。为此,我决定将“模块”(实际上只是 .php 文件)动态加载到一个旨在容纳它们的 div 中。

这适用于不依赖于特定 js 文件的模块,但有一个需要“participation.js”文件。

我在 body 指令上有一个 'onload="initSelectable()"' 的整个窗口中测试了该模块,但是当模块加载到管理仪表板时调用此函数不会执行任何操作。

这是 participation.js 的内容(它只是从 JQuery selectable 中复制/粘贴,我稍微修改了行为):

var selectedPlayerIDs = [];

function initSelectable(){
    $('#selectable').selectable();
    $('#submitParticipationBtn').hide();
    console.log("initSelectable");

    $("#selectable").selectable({
        stop: function() {
            var count = 8;
            var result = $("#selectedPlayersCount").empty();
            $(".ui-selected", this).each(function() {
                count--;
                selectedPlayerIDs.push($(this).attr("data-playerid"));
            });
            if(count > 1)
                $('#selectedPlayersCount').html(count + " more players");
            else if(count === 1)
                $('#selectedPlayersCount').html(count + " more player");
            else if(count === 0)
                $('#selectedPlayersCount').html("no more player. You're good to go !");
            else if(count === -1)
                $('#selectedPlayersCount').html(-count + " player less");
            else
                $('#selectedPlayersCount').html(-count + " players less");
            if(count === 0)
                $('#submitParticipationBtn').show();
            else
                $('#submitParticipationBtn').hide();
        }
    });
}

function submitParticipation(){
    alert( "JS loaded" );
    $.post("participation.php", {selectedIDs : JSON.stringify(selectedPlayerIDs)}, function() {

    })
    .onSuccess(function() {
        alert( "onSuccess" );
    })
    .fail(function() {
        alert( "error" );
    });
}

基本上这段代码初始化了 JQuery Selectable 环境。在 div 中加载模块时,我使用 $('#dynamicPage').hide().load("module1.php").fadeIn('500'); 直接跟 $.getScript("participation.js");

问题是,模块正确加载(至少 HTML 部分),我可以在控制台日志中看到(“initSelectable”)。但是我需要从命令中手动重新执行 initSelectable() 才能使其生效。当我这样做时,我看到控制台中记录了一个 undefined,在第二个(“initSelectable”)日志之前(这可能是因为我正在尝试调用 $('#selectable').selectable(); 第二次)。

例如这里是参与模块.php文件:

<div class="well">
    <h3>Create a participation</h3>
    <h4>Please select <span id="selectedPlayersCount">8 players</span></h4>
    <div class="row">
        <div class="col-sm-4">
            <ol id="selectable">
                <?php include_once "../Ctrl/rankingList.php" ?>
            </ol>
            <button class="btn btn-success" id="submitParticipationBtn" onclick="submitParticipation()">Submit</button>
        </div>
    </div>
</div>

我已经尝试了无数种不同的方式来调用 initSelectable 函数(回调、事件、超时等...),无论如何,即使它被浏览器执行,我仍然需要手动重新执行它让它工作...

所以基本上,我的问题是:

  • 将 HTML 和依赖的 JS 文件加载到 div 中的正确方法是什么?

最佳答案

What is the correct way to load HTML and dependant JS files into a div ?

所以,这将是一个好的开始,您可以从这里开始。

$(function() {

    $("#myDiv").load("myfile.php", function() {

        console.log("HTML has been injected!");
        //Get dependencies
        $.getScript( "myscript.js" )
        .done(function( script, textStatus ) {
            //Call methods from within myscript.js
            initSelectable();
        })
        .fail(function( jqxhr, settings, exception ) {
            console.log("There was an error!");
        });
    });

    // Remove inline event handler and bind it like below.
    $("#myDiv").on("click", "#submitParticipationBtn", submitParticipation);

    function submitParticipation() {
        //...
        //...
    }
});

我不确定为什么要复制 $('#selectable').selectable()。但是,它留给你来修复 :)

关于对 JQuery .load() 的 JavaScript 函数调用的行为与预期不符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30708121/

相关文章:

php - 如果密码或登录名不正确如何显示

javascript - 如何在 Bootstrap 中使用输入类型=密码的工具提示显示输入的密码?

php - 从远程 mysql 数据库检索图像到 android

javascript - 在 IFrame 中覆盖 window.open

javascript - 使用 adobe air 和 javascript 进行 Onchange 事件

javascript 如何通过 api 调用重定向 url 来获取 json 数据

php - 为什么调用未定义函数时没有 PHP 错误?

javascript - 三.js通过名称访问场景

javascript - 如何从非标记文本中获取最后几句的文本?

javascript - 导入 SASS 文件的测试组件时出现语法错误