有时select2无法正常工作/未在穆德插件中加载

我与moodle合作,并在其中创建了一个插件。在这一本书中,我使用了库select2

在插件的view.php文件中,我具有:

    foreach((array) $jsFiles as $path) {
    $PAGE->requires->js(new moodle_url($CFG->wwwroot . '/mod/exam/subplugins/'.$path));
}

?>

<!DOCTYPE html>
<!-- Essential to activate bootstrap -->


<html>
<head>
<link rel="stylesheet" type="text/css"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
    src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<link href="select2/select2.min.css" rel="stylesheet" />
<script src="select2/select2.full.js"></script>
<link href="select2/chart.min.css" rel="stylesheet" />
<script src="select2/chart.min.js"></script>
<title></title>
</head>
<?php

?>
</html>

<?php
echo $OUTPUT->footer();

所以,我在这里加载库。 我在javascript文件中使用它:

$(document).ready(function() {
    var script =  $.getScript("../../mod/exam/select2/select2.min.js");
    init();
});

第一次,我只是在ready函数中加载了脚本,但是现在我也在init函数中加载了脚本,这样做可以使它更频繁地工作。 而且我还有一个按钮来添加一个select2字段。并且我在脚本的顶部加载了$.getScript函数,以使其更频繁地工作。如果在大多数情况下单击按钮时都没有这样做,那么它将无法正常工作,并且我会遇到类似的情况:

有时select2无法正常工作/未在穆德插件中加载

在Windows 10上的本地计算机中,它在所有浏览器(chrome,firefox ...)上都能在10上工作9次

我在ubuntu的另一台机器上对其进行了测试,但实际上并非所有浏览器都能正常运行。 我也在Linux上的虚拟机上对其进行了测试,就像在localhost中一样。当我从Windows 10上的计算机访问它时,它在10上可以运行9次,而在ubuntu上的计算机上却无法运行。

当它不起作用时,出现以下错误:来自require.min.js的错误:Uncaught Error: Mismatched anonymous define() module: function(u){var e=function...,然后是我的JavaScript文件中的错误:createexam.js:98 Uncaught TypeError: $(...).select2 is not a function

我还尝试以类似$this->page->requires->js(...)或没有$.getScript函数的方法提供其他方式加载库。但是每次,它的工作频率都比现在少。

那么,您有一个主意,为什么它每次都不在所有机器上都起作用?还是我加载库的方式不好?

wangkvin 回答:有时select2无法正常工作/未在穆德插件中加载

我从没与Moodle合作,但与RequireJS合作。您的网站使用RequireJS,并且select2支持RequireJS。因此,您必须通过RequireJS进行加载。否则,RequireJS第一次加载时将不起作用-因此不时:)

使用RequireJS:

require(['select2/select2.full.js','select2/chart.min.js'],function () {
  $(document).ready(function() {
    var script =  $.getScript("../../mod/exam/select2/select2.min.js",function () {
      init()
    });
  });
});
本文链接:https://www.f2er.com/3157811.html

大家都在问