html中的click函数,如何在HTML中使用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();

});

});

编码风格是对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作为全局范围的一部分。代码难以理解,很容易被误解 - 所以我恳请你重构并正确完成它。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值