首页 > 解决方案 > 有时 select2 在 moodle 插件中不起作用/加载

问题描述

我与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函数顶部加载了该函数的脚本,以使其更频繁地工作。如果我在单击按钮时不这样做,大多数情况下,它不起作用,我有类似的东西:

选择2未加载

在 Windows 10 上的本地计算机上,它在 10 上使用所有浏览器(chrome、firefox ......)运行 9 次

我在另一台机器上的 ubuntu 上对其进行了测试,但它在所有浏览器上的运行频率并不高。我还在 linux 上的虚拟机上对其进行了测试,就像在 localhost 中一样。当我在 Windows 10 上从我的机器上访问它时,它在 10 上工作了 9 次,在 ubuntu 上的机器上,它真的很少工作。

当它不起作用时,我有这个错误: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提供的其他方式加载库。但每次,它的工作频率都比现在低。

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

标签: javascriptjqueryrequirejsjquery-select2moodle

解决方案


我从未使用过 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()
    });
  });
});

推荐阅读