javascript - jQuery call function with each item in selection -


i trying call 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 element has 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 data-value

$(document).ready(function () {     $(".can-click").click(function () {     var code = $(this).data("code");         $("output").each(display(code));     }); }); 

what wanting happen when click on anchor alert showing data-code anchor clicked , data-value each p, code attached woud want 3 alerts pop up.

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

here link code in jsfiddle http://jsfiddle.net/mikeu/xfd4n/

you have use . class-selectors , pass this object when calling display function like,

$(document).ready(function() {    $(".can-click").click(function(e) {      e.preventdefault();      var code = $(this).data("code");      $(".output").each(function() { // use . class selectors        display(code, this); // pass here      });    });  });    function display(code, ths) { // ths = this, current output element    var p = $(ths), // use ths instead of      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>


Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -