2

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>

Silkograph
  • 85
  • 2
  • 12
  • Using let is recommended pertaining to the new ES6 standards. – Ani Oct 19 '16 at 07:40
  • Let is not supported by all browsers. Your problem is the lack of closure – mplungjan Oct 19 '16 at 07:43
  • Yes, JJJ, mplungjan, It is already answered. Sorry to post it again without digging it enough. Now what? – Silkograph Oct 19 '16 at 07:52
  • 1
    Like this: `function createList() { var play_list = document.querySelector('#plist>ul'); var plist = player.getPlaylist(); var li = document.createElement("li"); for (var i = 0; i < plist.length; i++) { var plist_id = plist[i]; atag = document.createElement("a"); atag.innerHTML = i + "
    "; 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
  • It worked without any issue. I think now I got it correctly. – Silkograph Oct 19 '16 at 09:01
  • hi, mplungjan, Just a followup. I understand another way of resolving this problem by, js iife. ` atag[i].onclick = function (j) { return function() { console.log(j)}; }(plist_ids);` – Silkograph Oct 21 '16 at 05:50

0 Answers0