I am writing a JavaScript code to create YouTube Play list for a webpage. While writing a code I encountered a problem which I am bit aware but seems I did not understand it correctly yet.
The problem is, I am taking values from an array and passing it to init onclick event handler function. But when I click an object I don't get value I am passing to it. I get last value of an array object.
I know the solution, if I use let
instead of var
, I am getting expected results.
let plist_ids = plist[i];
instead of var plist_ids = plist[i];
I have two question. How do I get correct values in this case without using LET? If there is no easy solution, then is it okay to use LET?
<body>
<div id="plist" >
<ul>
</ul>
</div>
function createList() {
var play_list = document.getElementById('plist').children[0];
var plist = player.getPlaylist();
var atag =[];
var li = document.createElement("li");
for (i=0; i<plist.length; i++) {
var plist_ids = plist[i];
atag[i] = document.createElement("a");
atag[i].innerHTML = i + "<br>";
atag[i].href = "javascript: void(0);";
atag[i].onclick = function () {
console.log(plist_ids);
};
li.appendChild(atag[i]);
play_list.appendChild(li);
}
}
player = {
getPlaylist: function () {
return [1,2,3,4,5,6,7,8,9,10];
}
}
createList();
</script>
"; atag.href = "#"; atag.setAttribute("data-playlistid",plist_id); atag.onclick = function() { console.log(this.getAttribute("data-playlistid")); return false; }; li.appendChild(atag); play_list.appendChild(li); } }` – mplungjan Oct 19 '16 at 08:04