I have a JS script pop-up in a WP loop, but I can't get the right title to show
I have a sidebar on a WordPress site that lists a number of posts with audio files. When a user clicks on a "play" button in that sidebar, the associated audio file should load in a popup window that also shows a title for the audio being played. At the moment, I've placed the JS script inside the loop, but the popup is only loading what's last in the loop... The user clicks on the top audio link开发者_运维技巧 in the sidebar but gets the bottom one, basically.
I have an idea of why this happens, because the PHP runs on the server first, and the JS popup is just grabbing the latest item in the PHP loop. But I'm stuck... how do I make the popup grab the right audio post's info? Many thanks in advance for an answer.
I have to run, but without the code (as of this writing, there is no code in the question; hopefully that changes), I can guess at it. It's just a guess though.
I would say you're creating closures in a loop, like this:
for (index = 0; index < data.length; ++index) {
link = /* ...code to create the link... */;
title = data[index].title; // Or maybe it's on `link` itself
link.onclick = function() {
doNiftyPopup(title);
};
}
The anonymous function there is the closure. That would give you the symptom you're experiencing. When you create a closure, it has an enduring reference to the thing that it closes over (title
, for instance), not a copy of its value when the closure is created. And so all of those onclick
handlers will use the last value assigned to title
, which is of course the last one in the loop.
The fix is to give the closure something else to close over that won't get overwritten, like this:
for (index = 0; index < data.length; ++index) {
link = /* ...code to create the link... */;
title = data[index].title; // Or maybe it's on `link` itself
link.onclick = createHandler(title);
}
function createHandler(thisTitle) {
return function() {
doNiftyPopup(thisTitle);
};
}
Now, each call to createHandler
creates a closure over the thisTitle
argument that was created for that specific call — each closure gets its own thing to close over.
More here: Closures are not complicated
精彩评论