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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/jquery-exercises/jquery-events-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics