英语吧想法有些文章不一定是为了上首页投稿

Three Most Common jQuery Events

2019-07-29  本文已影响7人  此之木

On()

On() works similarly to addEventListener. It lets you specify the type of event to listen for.

If we want to style the h1 text content when h1 is clicked, we could write:

$(“h1”).on(“click”, function(){

$(“h1”).css(“color”, “green”);})

Inside on(), we give the type of event we want to listen for, in this case is “click”. Then, we pass a function to change the h1 style when the event happens.

If we want to bold the button text when the mouse is on that button, we will select “button”, then set “mouseenter” as event type, and pass a function which will make the text bold.

If we want the bold button back to normal, we only need to change the “mouseenter” to “mouseleave”, and change “bold” to “normal”.

What’s the difference between on() and click()?

In most case, click() and on(“click”) will both get the job done, but there is one key difference: click() only adds listeners for existing elements, but on() will add listeners for all potential future elements.

上一篇下一篇

猜你喜欢

热点阅读