Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

jQuery: Find the data passed with the on() method for each element

jQuery Events : Exercise-7 with Solution

Find the data passed with the on() method for each <p> element.
Sample Data :

HTML :

<p>Click on each header element to return the data passed with the on() method.</p>
 <h3>This is a header1.</h3>
 <h3>This is another header2.</h3> 

Sample Output :

Click on each header element to return the data passed with the on() method.

This is a header1.


This is another header2.

Header1. paragraph has Event data: 0

Header2. paragraph has Event data: 1

Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Click on each header element to return the data passed with the on() method</title>
</head>
<body>
<p>Click on each header element to return the data passed with the on() method.</p>
<h3>This is a header1.</h3>
<h3>This is another header2.</h3>
</body>
</html>

JavaScript Code:

$("h3").each(function(i){
   $(this).on("click", {x:i}, function(event){
     var info = "Header" + $(this).index() + ". paragraph has Event data: " + event.data.x;    
    $("<p>"+info+"</p>").appendTo( "body" );      
   });
});

Live Demo:

See the Pen jquery-events-exercise-7 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Click a header to add another.
Next: Change the background color of the <div> element of the following code on clicking the button.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.