Home >Web Front-end >JS Tutorial >Why Do All My Click Handlers Return 'Link 5'?
Javascript Infamous Loop Issue: Closure Unveils the Magic
The notorious loop issue arises when the code snippet attempts to create a collection of links with unique click handlers. Yet, every click registers as "link 5," casting a spell of bewilderment.
Closure: The Enigmatic Sorcerer
The riddle lies in JavaScript's scope, a realm bound by functions, not blocks. Closures, veiled sorcerers, ensnare the enclosing scope within their grasp.
The Flawed Loop
In the errant loop, the variable 'i' is confined within the function, incarcerated by a prison of closure. As the loop completes, 'i' transmutes into "5," leaving its ghostly imprint on the hapless handlers.
The Savior Loop
A glimmer of hope emerges from the second loop. Each iteration conjures an independent function object, each guarding its own sentinel 'num.' This imprint resists the mutagenic touch of time, shielding the handlers from the insidious spell of '5.'
An Optimized Trinity
While closure spurs this miraculous transformation, it demands an extravagant price - two fresh function objects per link. A more graceful solution arises from harnessing the DOM's secret knowledge. By storing data directly on the nodes, we conjure links with distinct memories, absolved from the tyranny of the outer scope.
The Arcane Elixir
The true enchantment lies in this potion of code:
function linkListener() { alert(this.i); } function addLinks() { for(var i = 0; i < 5; ++i) { var link = document.createElement('a'); link.appendChild(document.createTextNode('Link ' + i)); link.i = i; link.onclick = linkListener; document.body.appendChild(link); } }
Each link bears its own 'i,' whispering its unique identity into the allure of a click. Closure's magic, now wielded with precision, casts a spell of wonder, empowering links to recall their own destiny.
The above is the detailed content of Why Do All My Click Handlers Return 'Link 5'?. For more information, please follow other related articles on the PHP Chinese website!