0

I have html like this following:

<span class="product1 automaticAdds">Foo</span>
<span class="product2 automaticAdds">Foo</span>
<span class="product3 automaticAdds">Foo</span>

What I want to happen, is that when you click on a span, it calls the onclickfunction which is function2. However, the value of both ids and urltogo are both undefined. I have looked at and followed advice from other SO questions, but still not working. How can I get the correct values to pass?

$(document).ready(function() {

var uniqueProducts = document.getElementsByClassName("automaticAdds");
var urls=['http://www.aol.com','http://www.google.com','http://www.yahoo.com'];


for (var i = 0; i < uniqueProducts.length; i++) {
 var ids=i;

        $(".product" + ids).click((function(ids) {
            return function() { function2(ids,urls[ids]); };
    })()); //end click
} //end for



function function2(ids,urltogo){

console.log(ids);
console.log(urltogo);

}


}) //end everything
user2029763
  • 143
  • 3
  • 13
  • [Just add data attributes to the spans and attach the click event to the document. Much easier than iterating over a bunch of things](https://jsfiddle.net/q13f01qm/8/). – Andy Mar 29 '18 at 13:29

1 Answers1

0

You have to pass ids to the IIFE (Immediately Invoked Function Expression):

})(ids))

Working Code:

$(document).ready(function() {

  var uniqueProducts = document.getElementsByClassName("automaticAdds");
  var urls=['http://www.aol.com','http://www.google.com','http://www.yahoo.com'];

  for (var i = 0; i < uniqueProducts.length; i++) {
    var ids=i;

    $(".product" + ids).click((function(ids) {
      return function() { function2(ids,urls[ids]); };
    })(ids)); //end click
  } //end for



  function function2(ids,urltogo){
    console.log(ids);
    console.log(urltogo);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="product1 automaticAdds">Foo</span>
<span class="product2 automaticAdds">Foo</span>
<span class="product3 automaticAdds">Foo</span>
Mamun
  • 66,969
  • 9
  • 47
  • 59