0

I want to access variable linky below within a function for img#play. However, it is only taking on the last known value of linky, and I understand this is due to something called a Javascript closure. Googling and trying many different things such as return linky within img#play click function doesn't seem to work. I was also told variable song will suffer from the same problem. Anybody got any ideas on how to make the click function for img#play work for each separate linky rather than just the last?

  function doSearch() {

    var searchTerm = document.getElementById('search').value;

    // Search soundcloud for artists
    SC.get('/tracks', { q: searchTerm}, function(tracks) {
      for(track in tracks) {

        console.log(tracks[track]);

        var img = document.createElement('img');
        img.setAttribute("src", (tracks[track]["artwork_url"]));
        var title = tracks[track].title.replace("'", "\\\'").replace("\"", "\\\"");

        var song = document.createElement('div');

        var linky = document.createElement('a');
        linky.setAttribute("href", (tracks[track].permalink_url));

        img.setAttribute("onclick", "showTrackInfo('" + title + "\\n" + "\\n" + tracks[track].label_name + "\\n\\n" + "(click to close)" + "')"); 



        if (tracks[track]["artwork_url"] == null) {
          console.log(""); } 
        else { 

          var Catalog = document.getElementById('catalog');
          Catalog.appendChild(img);

          $('div#catalog').append('<img src="http://i.imgur.com/rGdvfl7.png" id="play">');


          $('img#play').click(function() {

            return this.linky;


          $.get(
            'http://soundcloud.com/oembed?' + 
            'url=' + linky + 
            '&format=json&maxheight=296'
            )

          .done(function (response) {
            song.innerHTML = response.html;
            document.getElementById("soundiframe").appendChild(song);

          });
          });
        }


      }
    });
  };

I need all the variables in the above code... If anyone has any clues on what to do that would be much appreciated.

4

1 回答 1

0

您可以创建另一个闭包:

(function(linky, song) {
  $('img#play').click(function() {
     ...
}(linky, song));

这将在创建闭包时保留 linky 的值。

于 2013-04-30T21:14:24.493 回答