Javascript problem involving multiple scopes in closures

What is the most effective solution for addressing this issue related to closure in JavaScript?

Here is a simple problem I am facing:

I have 10 spans with onclick events (I want an alert showing the number of the span clicked on each click):


var spans = document.getElementsByTagName('span');
function addEvents(divs) {
    for(var i=0; i < divs.length; i++) {
        divs[i].innerHTML = i;
        divs[i].onclick = function() { alert(i) };
    }
}
addEvents(spans);

You can also view the code in action on JSFiddle.

Answer №1

Enclose it within a self-invoking function:

buttons[i].onclick = (function(i) {
    return function() {
        console.log(i);
    };
})(i);

For brevity, set it as a callback:

var clickCallback = function(i) {
    return function() { console.log(i); };
};

buttons[i].onclick = clickCallback(i);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Js month picker problem encountered

I am currently working on implementing a month picker using the library called react-month-picker The code is functioning correctly in React: https://codesandbox.io/s/react-month-picker-forked-84rqr However, when I tried to integrate the same code into a ...

passport.authenticate method fails due to empty username and password values

I seem to be making a simple mistake while following a tutorial. Even though I believe I have followed all the steps correctly, when I submit the login form, I get redirected to the "failureRedirect" page. When I checked the source code in the passport mod ...

How to Set Up a Simple Gulp Uglify Configuration

My objective is to compress all .js files within my project and save a minified version in the same directory. Assuming this is the structure of my project directory: project/ gulpfile.js basic.js Project/ Project.js Toolbelt. ...

How can we bring in a function into a Vue component?

I'm currently facing an issue with importing a single function into my Vue component. To tackle this problem, I separated the function into its own js file: randomId.js: exports.randomId = () => //My function ... Within my Vue component, I attem ...

Continuously update scrolling functionality

Could you please provide more information about the solution mentioned in the following question? I am facing a similar issue. jQuery’s css() lags when applied on scroll event Regarding solution #3 ->> To ensure continuous updates, it is suggeste ...

What is the best way to transfer variables between two Vue files?

How can I transfer a variable between two Vue files? Hello, in my SendCode.vue file, I have a variable named NewEmail that I would like to use in another file called changePass.vue. Is there any way to do this? Can someone offer assistance? Thank you</p ...

Building New Web Pages with Express in Node.JS

I want to dynamically generate a new page on Node.JS with Express upon user form submission. Here is my initial approach, but it's not working as expected: var app = require('express')(); var server= require('http').createServer(a ...

In PHP/HTML, if the URL is domain.co.uk/?debug, then the following action will

Apologies for what may seem like a basic question, but I've been searching for a clear answer with no luck! My goal is simple - when someone goes to , I want to show extra details, like the code version or any other notes I include. Once again, sorr ...

Is it feasible to cancel or clear the queue for a jQuery fadeOut function after a delay is specified? If so,

Can anyone help me out with this question? Is there a way to eliminate the delay in chaining? Mn.Base.TopBox.show = function(timedur){ $('#element').fadeIn().delay(timedur).fadeOut(); } Mn.Base.TopBox.cancelFadeout = function(){ } I&apos ...

Custom time selector does not automatically set the default value

After creating two inputs where one represents hours and the other minutes, clicking on edit should display the total time in seconds. The original time for editing should remain unchanged until you choose to save it. Here is the link to the code: https:// ...

Navigating to a new page once a backend function in Express has finished executing

Recently, I have been experimenting with express web servers to create a website that allows users to sign in using Discord's OAuth2 API. In order to secure sensitive information, I have been utilizing the express-session npm module to store data with ...

Fetching user feeds from Facebook with AngularJS is easier than you think

I have searched through multiple articles but have yet to find a solution for this particular issue. My goal is to retrieve user feeds from Facebook. How can I achieve this? Below is my code: var newMod = angular.module('newapp', []); newMod.c ...

Identifying whether a Property in an Object is another Object

I'm planning to utilize JSON for stringifying the value of a property within an object, which will then be stored as a Tag on Google Calendar using Google Apps Script. The value in question is actually a double-nested Object (look at extraAttributes w ...

Twice the calls are being made by jQuery Ajax

I am using an <input> tag with the following attributes: <input type="button" id="btnSave2" value="Save" onclick="Event(1)" class="btn btn-primary col-lg-12" /> In addition, I have a script as ...

The website encountered an error in loading with the error message "ENOTFOUND" in Cypress

All my cypress tests were running smoothly until one day they all failed to visit the target site. The error message that I received was: cy.visit() failed trying to load: https://mywebsite.com/accounts/login/ We attempted to make an http request to this ...

A guide on calling a function from a different component in vuejs2

I am facing a situation where I need to trigger an event whenever my sidebar opens. This event should be called every time the sidebar is opened. For example, when I click on an element, it triggers the opening of my sidebar which then calls a function th ...

Tap and hold with Zepto

I've been on the hunt for a Zepto plugin that can handle a longClick event. While Zepto already supports longTap, which is perfect for mobile devices, I need something specifically for desktop browsers when a user clicks and holds. It's also impo ...

Automatically move to the latest message as soon as it is posted

After trying multiple codes and encountering issues, I am attempting to add my message in a textarea that will automatically scroll down. Even though I have my own codes, they don't seem to work properly. I also tried using the code provided Here. ED ...

Stopping npm private organization from releasing public packages

Is there a method to restrict the publication of public packages within an npm organization? It appears that this scenario would often arise (ensuring that no member of an organization accidentally publishes a package as public when it should be private b ...

Guide to using Angular $resource to pass query parameter array

My goal is to implement a feature that allows users to be searched based on multiple tags (an array of tags) using the specified structure: GET '/tags/users?tag[]=test&tag[]=sample' I have managed to make this work on my node server and hav ...