如何在HTML中使用onclick调用此函数?

时间:2015-07-06 21:36:44

标签: javascript jquery html

我刚刚开始维护某些代码,我不确定这里是什么。

$(document).ready(function () {

     function Test() {

        var that = this;
        that.testFunc = function() {
        }
     }    
}

我想从HTML执行testFunc onclick。我该怎么做呢?无论如何我还可以简化这个吗?我对这种编码风格感到困惑

3 个答案:

答案 0 :(得分:2)

不要使用<button onclick="...">。如果您正在使用jQuery,请使用selectors获取元素并设置event listener

$('button').click(function(){
    ...
});

你发布的代码有些愚蠢,而且不易阅读。它可以使用重构。

如果你坚持要离开它,你可以这样做......:

$(document).ready(function () {
     function Test() {
        var that = this;
        that.testFunc = function() {
            //alert('i will also fire when this.testFunc() is called.');
        }

        // alert('i will fire');
        this.testFunc();
     }  

    $('button').click(function(){
       Test(); 
    });
});

Here's a fiddle of that working.

编码风格是对OO-J​​avascript的不良尝试。 W3Schools (我知道......)可能是一个开始了解它的全部内容的好地方。或者,this post on Stack完全与this关键字有关,并且包含一些指向优质资源的链接。

TLDR;代码看起来非常聪明,但只是令人困惑和垃圾。

<强>更新

好的,所以这里发生了什么。

$(document).ready(function () {        // when the page is loaded, run this function
    function Test() {                  // create a named function called Test. 
                                       // Note that this function is only visible (so can only be called) within the anonymous function being run after $(document).ready.
        var that = this;               // set a variable ('that') to 'this' - a special keyword. At this point, 'this' will refer to the Global scope.
        that.testFunc = function() {   // create a function called testFunc on the object which is now 'that' - i.e. Global scope, the Window object.
                                       // basically, create window.testFunc.
            //alert('i will also fire when this.testFunc() is called.');
        }

        // alert('i will fire');
        this.testFunc();               // call window.testFunc();
    }  

    $('button').click(function(){
        Test();                        // run the Test function explained above
    });
});

所以,如果你不进行重构,你需要做类似的事情:

$(document).ready(function(){
    function Test(){
        var that = this;
        that.testFunc = function(){
            ...
        };
    }

    $('button').click(function(){
        testFunc();
    });
    Test();
});

基本上,您需要运行Test()来创建testFunc作为全局范围的一部分。代码难以理解,很容易被误解 - 所以我恳请你重构并正确完成它。

Here's (another) fiddle按钮只需拨打testFunc

答案 1 :(得分:0)

执行此操作的最佳方法是在jQuery中使用.click()方法。

$('.element').click(testFunc);

如果您需要/需要使用HTML onClick属性:

<input type="button" onclick="testFunc();" />

答案 2 :(得分:0)

只需从处理程序调用{​​{1}}即可,因为testFunc()已分配给窗口上下文。也就是说,假设在某个时刻调用testFunc

JSFiddle Example

相关问题