The course summarized three most important and useful jQuery events which could use 99% of the time.
These three events are: click(), keypress(), and on().
Click
In jQuery, click() method is a quick and easy way to add a click listener to element(s).
$(“selector”).click(function(){
run some code});
Recall the click event in JavaScript, we have to do document.querySelector() first, then addEventListener, and give a function. The jQuery one looks much easier to apply.
I create a simple HTML page with some buttons. I will show you how to use click() method to make actions on page.
Then, I check whether jQuery file is connected correctly.
If I want to get an alert when I click on h1, I will use “$” to select h1, then add alert message inside click() function:
$(“h1”).click(function(){
alert(“h1 is clicked”);})
As the result, when you click the h1 text, the page will pop up the alert message.
We can write the same event function to button, too. All we need is to change “h1” to “button”.
We can also add some style when the button is clicked:
$(“button”).click(function(){
$(this).css(“background”, “pink”);})
If we want to refer to the button that was clicked, we need to use $(this), which is the jQuery wrapper. As the result, when we click the button, it add a pink background.
网友评论