I am trying to call a function using each object found in jQuery selection
<a href="#" class="can-click" data-code="a">a</a>
<a href="#" class="can-click" data-code="b">b</a>
<a href="#" class="can-click" data-code="c">c</a>
<a href="#" class="can-click" data-code="d">d</a>
Each a
element has a data-code value:
<p class="output" data-value="1"></p>
<p class="output" data-value="2"></p>
<p class="output" data-value="3"></p>
Each p
element has a data-value:
$(document).ready(function () {
$(".can-click").click(function () {
var code = $(this).data("code");
$("output").each(Display(code));
});
});
What I want is that when you click on the anchor a
you will get an alert showing you the data-code from the anchor clicked and the data-value for each p
, with the code attached I want 3 alerts to pop up.
function Display(code) {
var p = $(this);
var value = p.data("value");
alert(code + " " + value);
}
Here is a link to the code in jsfiddle: http://jsfiddle.net/mikeu/XFd4n/
You have to use .
for class-selectors and pass this
object when you are calling Display
function like,
$(document).ready(function() {
$(".can-click").click(function(e) {
e.preventDefault();
var code = $(this).data("code");
$(".output").each(function() { // use . for class selectors
Display(code, this); // pass this from here
});
});
});
function Display(code, ths) { // ths = this, current output element
var p = $(ths), // use ths instead of this
value = p.data("value");
console.log(code + " " + value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="can-click" data-code="a">a</a>
<a href="#" class="can-click" data-code="b">b</a>
<a href="#" class="can-click" data-code="c">c</a>
<a href="#" class="can-click" data-code="d">d</a>
<p class="output" data-value="1"></p>
<p class="output" data-value="2"></p>
<p class="output" data-value="3"></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With