在jQuery中使用.click()与使用onclick调用函数 [英] Using .click() in jquery vs calling a function using onclick

查看:1588
本文介绍了在jQuery中使用.click()与使用onclick调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对jQuery很陌生,但是我想知道使按钮做某事时的最佳实践是什么.

I'm rather new to jQuery but i want to know what the best practice is when making a button do something.

我应该使用.click()

Should i use .click()

HTML

<button id="submit" class="btn btn-default">Submit</button>

JS

$('#submit').click(function(){
    //DO SOMETHING
});

或调用函数

HTML

<button class="btn btn-default" onclick="Submit();">Submit</button>

JS

function Submit() {
    //DO SOMETHING
}

我的问题是,这两种方法的行为是否相同?如果不是,那么,一种方法相对于另一种方法有什么优势.

My question is, do these two methods behave the same way? If not, what are the advantages of one over the other.

*我已经尝试过并且似乎以相同的方式工作,但是对于jQuery来说我是新手,所以我想确定一下.

*I've tried and seems to work the same way but being new to jQuery i wanted to make sure.

推荐答案

它们的行为方式(内部)不同.

They do not behave the same way (internally).

使用onClick可以将click事件直接绑定到功能上,这在性能上要好得多.

Using onClick binds the click event directly to a function which is slighly better for performance.

JQuerys .click()添加了一个事件侦听器,该侦听器具有多个优点(除了更具可读性之外).

JQuerys .click() adds an event listener which has several advantages (besides being more readable).

  • 它允许为一个事件添加多个处理程序.这对于即使使用其他库/扩展也需要正常工作的DHTML库或Mozilla扩展特别有用.
  • 当侦听器被激活时(捕获与冒泡),它可以使您对相位进行更细粒度的控制
  • 它适用于任何DOM元素,而不仅仅是HTML元素.

有关更多详细信息,请参见以下答案: jQuery.click()vs onClick

See this answer for more in depth info: jQuery.click() vs onClick

这篇关于在jQuery中使用.click()与使用onclick调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆