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



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

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

我已经测试了模块在整个窗口,那里有一个'onload="initSelectable()' '在body指令上,但是当模块被加载到管理仪表板中时调用这个函数不会做任何事情。

这是participant .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中?

如何将HTML和依赖的JS文件加载到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()被复制。但是,它留给你来解决:)

好吧,我做错了。我认为把<script src "path/to/script.js"></script>在模块文件不起作用。但实际上,它确实如此,我只需要在JS文件中调用$(document).ready(initSelectable())来确保initSelectable在正确的时间被执行。

现在我的。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>
    <script src="../Ctrl/participation.js"></script>
</div>

谢谢你的帮助:p

最新更新