JQuery call function with each item in selection

I am trying to call a function using every 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 item 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 to do is that when you click on anchor a you will get a warning showing you the data code from the click of the anchor and the data value for each p, with the code attached by woud, I want 3 warnings.

 function Display(code) { var p = $(this); var value = p.data("value"); alert(code + " " + value); } 

here is the link to the code in jsfiddle http://jsfiddle.net/mikeu/XFd4n/

+7
source share
2 answers

You must use . for class selectors and pass the this object when calling the Display function, for example,

 $(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> 
+5
source

Try the following: -

You need to pass the function link to the obj.each callback. obj.each(Display(code)) is incorrect, it must be obj.each(Display) ; but since you want to pass a variable here, you can call it inside an anonymous function.

Demo

  $(".output").each(function(){ Display(code, this)}); }); 

Script

 $(document).ready(function () { $(".can-click").click(function () { var code = $(this).data("code"); $(".output").each(function(){ Display(code, this)}); }); }); function Display(code,$this) { var p = $($this); var value = p.data("value"); alert(code + " " + value); } 
+4
source

All Articles