在自定义 joomla 模块中包含 javascript 函数

Including a javascript function in a custom joomla module

我有一个工作代码笔,它使用了一些 javascript https://codepen.io/cbold/pen/jOWONKO

我正在努力理解将 javascript 函数包含在我的自定义 Joomla 模块中的正确 method/syntax。

我已经阅读了官方文档,但它并没有让我更清楚

https://docs.joomla.org/J3.x:Adding_JavaScript_and_CSS_to_the_page

我还查看了 Whosebug 上发布的其他几个类似问题,但我对 examples/answers 的任何理解都不足以将它们应用到我的模块中。

我试图将函数作为一个单独的文件包含在内,并用我的 mod_mymodule.php 调用它:

$document = JFactory::getDocument();
$document->addScript(JURI::root(true)."modules/mod_mymodule/js/ mod_mymodule.js");

这是mod_mymodule.js中的javascript:

function clickHandler(target) {
    // Get the element that should be selected
    const elem = document.querySelector(target);
    // There were no elements to be selected
    if (!elem) return;
    // Get the old selected element (if any)
    const prevElem = document.querySelector('.selected');
    if (prevElem) {
        // If there was a previously selected element, it isn't anymore
        prevElem.classList.remove('selected');
    }
    // Make the new element selected
    elem.classList.add('selected');
}

函数没有发生。

我都试过了 document.querySelector(target);和 document.querySelector('#target');

我也试过在模块的末尾包含函数 default.php

<script type="application/javascript">
function clickHandler(target) {
    // Get the element that should be selected
    const elem = document.querySelector(target);
    // There were no elements to be selected
    if (!elem) return;
    // Get the old selected element (if any)
    const prevElem = document.querySelector('.selected');
    if (prevElem) {
        // If there was a previously selected element, it isn't anymore
        prevElem.classList.remove('selected');
    }
    // Make the new element selected
    elem.classList.add('selected');
}
</script>

但运气不好。

我再次尝试了 document.querySelector(target);和 document.querySelector('#target');

我很确定我的