Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从外部js文件调用OnClick()Jquery函数_Javascript_Jquery - Fatal编程技术网

Javascript 从外部js文件调用OnClick()Jquery函数

Javascript 从外部js文件调用OnClick()Jquery函数,javascript,jquery,Javascript,Jquery,我正在编写一个jQuery文件,使用onClick()作为按钮的事件。但我想从外部js文件加载另一个js函数。我该怎么做?我一直在努力,但没有结果 这是我的main.js $(document).ready(function(){ $("#dashboard").on("click", function(event){ event.preventDefault(); $('#content').html(dashboardTemplate);

我正在编写一个jQuery文件,使用onClick()作为按钮的事件。但我想从外部js文件加载另一个js函数。我该怎么做?我一直在努力,但没有结果

这是我的main.js

$(document).ready(function(){
    $("#dashboard").on("click", function(event){
        event.preventDefault();
        $('#content').html(dashboardTemplate);
        // I want another js external file will be loaded here

    });
});
这是我的外部js文件:元素#btnAddGroup位于dashboardTemplate内部,它只是一个html文件

    $("#btnAddGroup").on("click", function (event) {
        event.preventDefault();
        alert('test');
    });
多谢各位


编辑:根据你的建议

external.js

function addGroup(){
    $("#btnAddGroup").on("click", function (event) {
        event.preventDefault();
        alert('test');
    });
}
main.js

$(document).ready(function(){
    $("#dashboard").on("click", function(event){
        event.preventDefault();
        $('#content').html(dashboardTemplate);
         $.getScript('external.js', function() {
            addGroup();
        });

    });
}))

它仍然不起作用。我正在尝试排除故障。 再次感谢

您可以这样试试

假设这是您的
external.js
文件

function () funcEx(){
     console.log("This is logging from external function");
    }
$.getscript("path/to/jsFile",function(){
 funcEx();
});
您可以通过这种方式在
main.js
文件中调用
external.js
文件的函数。 假设这是您的
main.js
文件

function () funcEx(){
     console.log("This is logging from external function");
    }
$.getscript("path/to/jsFile",function(){
 funcEx();
});

希望您能有一个想法

您正在尝试将事件侦听器添加到一个尚未存在的元素,因为在您单击创建
btnAddGroup
元素之前已加载外部文件,因此事件将永远不会被附加和触发,但是,您可以将onClick listener添加到文档中,并使用jquery 1.7+检查是否单击了正确的元素,它将如下所示:

$(window).on("click", "#btnAddGroup", function (event) {
   event.preventDefault();
   alert('test'); 
 });

您控制外部文件有什么问题?@RokoC.Buljan我尝试了getScript,但没有成功。你能看看我上面的代码吗?我编辑它。谢谢。我试过了,但没有成功。请看上面我的代码,你期待什么?我是说你的要求是什么?否则,该代码应该可以正常工作。你能发布你的完整代码并解释你想要的是什么吗?上面的代码就是我现在拥有的全部。基本上,当我单击仪表板模板中的btnAddGroup按钮时,我会看到一个警报(“测试”)。偶数单击btnAddGroup存储在外部js中。我更新了代码。但仍然不起作用如果您在加载外部文件时使用代码加载外部文件,并使用文档侦听器或窗口侦听器,则应该可以正常工作,除非您的
警报
功能被阻止,或者模板文档是iframe或来自不同的来源谢谢您的建议。我将花更多的时间来了解原因。尝试使用
console.log
并检查console,而不是alert