Home > Net >  How can i pass the Array obtained from "each" inside the "click" function?
How can i pass the Array obtained from "each" inside the "click" function?

Time:02-05

$('.menu-colors_page > span').each(function () {
    var arr_color = [];
    arr_color.push($(this).attr('class'));

    $(this).click(function (arr_color) {
         console.log(arr_color);
    });
});

I tried like this but it doesn't work

Q: How to call arr_color inside click? q: How can i pass parameter from "each" function to "click" function?

CodePudding user response:

I'm not sure what you're trying to do here, but if you simply want to pass the variable arr_color to the click listener, you should not add that arr_color as the parameter of the .click handler function since the variable will be replaced by the handler and interpreted as an event as told in the documentation. To fix this, you could just simply remove the arr_color from the handler, like this:

$(document).ready(function() {
  $('.menu-colors_page > span').each(function() {
    var arr_color = [];
    arr_color.push($(this).attr('class'));

    $(this).click(function() {
      console.log(arr_color);
    });
  });
});
<script src="https://code.jquery.com/jquery-3.6.3.min.js" crossorigin="anonymous"></script>
<div >
  <span >span1</span>
  <span >span2</span>
</div>

CodePudding user response:

Maybe like this:

var arr_color = []; /* global variable */
$(document).ready(function() {
  $('.menu-colors_page > span').each(function() {
    arr_color.push($(this).attr('class'));
  });  
  $('.menu-colors_page > span').click(function() {
      console.log(arr_color);
  });
});
span{
  padding:2px;
  margin:1px; 
  color:white;
  cursor:pointer;
}
.red{
  background-color:red;
}
.green{
  background-color:green;
}
.blue{
  background-color:blue;
}
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<div >
  <span >span blue</span>
  <span >span green</span>
  <span >span blue</span>
</div>

  • Related