有时 select2 在 moodle 插件中不是 working/loaded

Sometimes select2 is not working/loaded in moodle plugin

我和 moodle and I created a plugin in it. In this one I used the library 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 函数的脚本,以使其更频繁地工作。如果我在单击按钮时不这样做,大多数情况下,它不起作用,我有类似的东西:

在我的本地机器上 windows 10 它在所有浏览器(chrome、firefox...)上在 10 上工作了 9 次

我在 ubuntu 上的另一台机器上对其进行了测试,它在所有浏览器上的工作效率并不高。 我还在 linux 上的虚拟机上测试了它,就像在本地主机上一样。当我在 windows 10 上从我的机器访问它时,它在 10 上工作了 9 次,在 ubuntu 上的机器上工作了 9 次,它很少工作。

当它不起作用时,我有这个错误:Uncaught Error: Mismatched anonymous define() module: function(u){var e=function... 来自 require.min.js 之后,这个:createexam.js:98 Uncaught TypeError: $(...).select2 is not a function 来自我的 javascript 文件。

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

那么,您知道为什么它不是每次都在所有机器上都有效吗?还是我加载库的方式不对?

我从未使用过 Moodle,但我使用过 RequireJS。您的网站使用 RequireJSselect2 支持 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()
    });
  });
});

显然是moodle js缓存的原因。 管理->外观->ajax和javascript->关闭缓存。