Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.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 从html调用js namesapce函数_Javascript_Jquery_Html - Fatal编程技术网

Javascript 从html调用js namesapce函数

Javascript 从html调用js namesapce函数,javascript,jquery,html,Javascript,Jquery,Html,从下面的问题可以明显看出,我是html/js新手,请原谅我之前问过这个问题 我所要做的就是从html调用在命名空间中定义的js函数,但我无法让它工作 当我点击“Alert!!”按钮时,它应该会调用sample.js文件中定义的myAlert函数,但它不起作用。你能帮我吗 这是我的sample.js文件 var mytest = mytest || {}; (function ($) { function youhere() { alert("You are Here!!"

从下面的问题可以明显看出,我是html/js新手,请原谅我之前问过这个问题

我所要做的就是从html调用在命名空间中定义的js函数,但我无法让它工作

当我点击“Alert!!”按钮时,它应该会调用sample.js文件中定义的myAlert函数,但它不起作用。你能帮我吗

这是我的sample.js文件

var mytest = mytest || {};
(function ($) {
    function youhere() {
        alert("You are Here!!");
    }
    function myAlert() {
        alert("YouMadeIt");
    }
    function funcInit() {
        youhere();
    }
    mytest.funcInit = funcInit;    
}(jQuery));
和html文件:

<!DOCTYPE html>
<HTML>
    <HEAD>
        <TITLE>Sample</TITLE>
        <script type="text/javascript" src="./js/jquery-1.11.0.min.js"></script>
        <script type="text/javascript" src="./js/sample.js"></script>
    </HEAD>

    <script>
        $(document).ready(function() {
            mytest.funcInit();
        });
        function testBtnClk() {
            mytest.myAlert();
        }        
    </script>
    <BODY>        
        <input type="button" id="testbtn" onclick="testBtnClk();" value="Alert!!" />
    </BODY>
</HTML>

样品
$(文档).ready(函数(){
mytest.funcInit();
});
函数testBtnClk(){
mytest.myAlert();
}        

因为
myAlert
不是
mytest
的属性

函数
myAlert
是一个仅存在于IIFE内部的关闭函数,在IIFE外部无法访问。因为您有一个全局名称空间,所以可以将函数引用添加到该名称空间中,以便可以使用该引用在IIFE之外调用该方法

var mytest = mytest || {};
(function ($) {
    function youhere() {
        alert("You are Here!!");
    }

    function myAlert() {
        alert("YouMadeIt");
    }

    function funcInit() {
        youhere();
    }
    mytest.funcInit = funcInit;
    mytest.myAlert = myAlert;
}(jQuery));

演示:

谢谢!!这很有效。我以前尝试过类似的方法,但它会自动调用myAlert()函数。可能是我在ready函数中定义的。谢谢你的帮助!!