Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/369.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.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 Onclick调用封装函数的html属性_Javascript_Jquery - Fatal编程技术网

Javascript Onclick调用封装函数的html属性

Javascript Onclick调用封装函数的html属性,javascript,jquery,Javascript,Jquery,如何使用html属性调用封装的jQuery函数 HTML <input type="submit"> 脚本 (function($) { function processForm() { alert('You rang?'); } })(jQuery); 你不能。您可以更改应用onclick的范围,但是: HTML <input type="submit"> 您需要将事件和函数放在同一范围内 <input type="s

如何使用html属性调用封装的jQuery函数

HTML

<input type="submit">

脚本

(function($) {

    function processForm() {
        alert('You rang?');
    }

})(jQuery);

你不能。您可以更改应用onclick的范围,但是:

HTML

<input type="submit">

您需要将事件和函数放在同一范围内

 <input type="submit" class="inputTarget">

(function($) {
            $(".inputTarget").on("click",function(){
              processForm();
            });

            function processForm() {
                alert('You rang?');
            }

})(jQuery);

(函数($){
$(.inputTarget”)。在(“单击”,函数(){
processForm();
});
函数processForm(){
警惕(“你打电话了?”);
}
})(jQuery);

此代码
(函数($){……})(jQuery)
被称为闭包,这意味着它内部的所有代码对外部世界都不可用。您需要将该函数设置为全局函数,或者确保全局变量指向该函数。社区已经为您提供了答案。作为一种编码标准,您需要将JavaScript和HTML代码分开。因此,在jquery中绑定click事件是正确的方法。但出于某种原因,如果您真的只想在HTML中使用
onclick
,请将此行
function processForm(){
替换为
window.processForm=function(){
,然后在HTML
onclick=“window.processForm()”
中替换为
window
。这里
window
是一个全局变量。