jQuery on("click",function()) 和 onclick="function();" 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17961154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:16:36  来源:igfitidea点击:

What is the difference between on("click",function()) and onclick="function();"?

javascriptjqueryhtmlevent-handling

提问by olli

So if I want something to happen when I click a button I can either do:

因此,如果我希望在单击按钮时发生某些事情,我可以执行以下操作:

<!-- EXAMPLE A-->
<input type="button" onclick="alert('hello world');">

or I can do

或者我可以

<!-- EXAMPLE B-->
<input type="button" id="clickme">
<script>
   $('#clickme').on("click",function(){alert('hello world');});
</script>

Or of course any variations (on change, on hover) and shortcuts (.click().change()) are possible...

或者当然任何变化(on change,on hover)和快捷方式(.click().change())都是可能的......

Besides the fact that A is shorter, what are the differences? Which is better and why?

除了 A 更短这一事实之外,还有什么区别?哪个更好?为什么?

I noticed, that when I use .html()to dynamically add an element to the site (like a button) B doesn't work for this newly created button, and I need to use A...

我注意到,当我使用.html()动态向站点添加元素(如按钮)时,B 不适用于这个新创建的按钮,我需要使用 A...

Any insights would be helpful!

任何见解都会有所帮助!

回答by Sushanth --

<input type="button" onclick="alert('hello world');">

This is the way how inline events are handled. The main reason this is a bad idea is to clearly define the separation of concerns.

这就是处理内联事件的方式。这是一个坏主意的主要原因是要清楚地定义separation of concerns.

HTML - Structure of your page

JS   - Your page functionality

This will cause less maintenance issues in the long run and when the system scales in size.

从长远来看,当系统规模扩大时,这将减少维护问题。

What happens if you have 100 buttons on your page and you want to remove the click event or change it for all of them. It would definitely be a nightmare. Also you can only define a single event if you bind it inline.

如果您的页面上有 100 个按钮,并且您想删除单击事件或为所有按钮更改它,会发生什么情况。这绝对是一场噩梦。此外,如果您内联绑定它,您只能定义一个事件。

By moving out to a separate file you have a lot of flexibility and you can just make a small change that will affect all the elements on the page.

通过移出到一个单独的文件,你有很大的灵活性,你可以做一个小的改变,这将影响页面上的所有元素。

So the 2nd approach is always better.and the way to go.

所以第二种方法总是更好。和要走的路。

By defining the events like below

通过定义如下事件

$('#clickme').on("click",function(){alert('hello world');});

you HTMLlooks clean sans of any functionality and removes the tight coupling.

HTML看起来很干净,没有任何功能,并消除了紧密的耦合。

In the cases you have a dynamically added, it is true inline events always work but there is a concept called Event Delegation. You attach the event to a parent container that is always present on the page and bind the event to it. When the event occurs at a later time on the element , the event bubbles to the parent which handles the event for you.

在您动态添加的情况下,确实内联事件始终有效,但有一个称为事件委托的概念。您将事件附加到页面上始终存在的父容器并将事件绑定到它。当事件稍后在 element 上发生时,事件会冒泡到为您处理事件的父级。

For such cases you bind the events using .onpassing in a selector

对于这种情况,您可以使用.on传入选择器来绑定事件

$(document).on('click', '#clickme', function() {

Keep in mind that binding multiple events to a document is a bad idea. You can always use the closestStaticAncestorto bind the events.

请记住,将多个事件绑定到一个文档是一个坏主意。您始终可以使用closestStaticAncestor来绑定事件。

回答by go-oleg

The first approach only lets you register one click listener whereas the second approach lets you register as many as you want.

第一种方法只允许您注册一个单击侦听器,而第二种方法允许您注册任意数量的监听器。

If you want clicks on dynamically added elements to be heard as well, you should use .on(). Here's some code that demonstrates this (jsfiddle):

如果您还希望听到对动态添加的元素的点击,您应该使用.on(). 这是一些演示这一点的代码(jsfiddle):

HTML

HTML

<div id="mainDiv">
<span class="span1">hello</span>
</div>

JS

JS

$(document).on("click", ".span1", function () {
   $( "#mainDiv" ).append("<span class=\"span1\">hello</span>");
});

$(".span1").click( function () {
   console.log( "first listener" );
}); 

$(".span1").click( function () {
   console.log( "second listener" );
}); 

Notice that first listenerand second listeneris only printed when clicking on the first hello, whereas a new spangets added when clicking on any of the spans.

请注意,first listenerandsecond listener仅在单击第一个 hello 时打印,而span在单击任何跨度时会添加一个新的。

回答by Samuel Liew

Guessing this is your real question:

猜猜这是你真正的问题:

I noticed, that when I use .html() to dynamically add an element to the site (like a button) B doesn't work for this newly created button, and I need to use A...

我注意到,当我使用 .html() 向站点动态添加元素(如按钮)时,B 不适用于这个新创建的按钮,我需要使用 A...

Simply use the selector in the .on()function, AND USE A CLASSinstead of DUPLICATE IDsfor multiple elements:

只需在.on()函数中使用选择器,并为多个元素使用类而不是重复 ID

$('document').on("click", ".myButtons", function(){
    alert('hello world');
});

Button(s) - change to class (if you use IDs, only the FIRSTwill be selected):

按钮 - 更改为类(如果您使用 ID,则只会选择第一个):

<input type="button" class="myButtons" />
<input type="button" class="myButtons" />

This is how you should use .on()to attach event handlers to new elements:

这是您应该如何.on()将事件处理程序附加到新元素:

https://stackoverflow.com/a/14354091/584192

https://stackoverflow.com/a/14354091/584192

回答by Ishan Jain

Difference in works, if you use click() you can add several fn, but if you use attribute only one function will be executed - the last one

工作上的不同,如果你使用click()你可以添加几个fn,但是如果你使用attribute只会执行一个函数——最后一个

HTML-

HTML-

<span id="JQueryClick">Click #JQuery</span> </br>
<span id="JQueryAttrClick">Click #Attr</span> </br>

Js-

JS-

$('#JQueryClick').on("click", function(){alert('1')});
$('#JQueryClick').on("click", function(){alert('2')});

$('#JQueryAttrClick').attr('onClick'," alert('1')" );//this doesn't work    
$('#JQueryAttrClick').attr('onClick'," alert('2')" );

If we are talking about performance, in any case directly using is always faster, but using of attribute you will be able to assign only one function.

如果我们谈论性能,在任何情况下直接使用总是更快,但使用属性您将只能分配一个功能。

Try This

尝试这个

Reference

参考