简体   繁体   中英

Sending parameter without function init

I have code which collects elements with class .colors

var colors = document.querySelectorAll('.colors');

And loop which assigns event to all that elements.

for (var i=0;i<colors.length;i++) {
    var color = colors[i];
    color.addEventListener('click', remember(color.getAttribute('id')), false);
}

How can I send parameter (in this sample- 'color.getAttribute('id')') to function (in this sample- 'remember') without her initiation?

function remember(color_value) {
  localStorage.setItem('color', color_value); }

Functional parameters can't be passed directly to event listener's. Instead instantiate a simple function and pass the parameter like below.

 function remember(id) { console.log(id); } var colors = document.querySelectorAll('.colors'); for (var i = 0; i < colors.length; i++) { var color = colors[i]; color.addEventListener('click', function() { remember(this.getAttribute('id')) }, false); } 
 .colors { padding: 5px 10px; background-color: lightgreen; } 
 <div id="div1" class="colors">Click Me - I'm Div 1</div> <br> <div id="div2id" class="colors">Click Me - I'm Div 2</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM