2015-12-03 38 views
0

我有一個Ajax調用,它返回一個電影標題數組。我想點擊每個標題旁邊的按鈕,並將標題添加到「正在觀看」列表中。我的「添加」鏈接似乎不接受事件處理程序。我能做些什麼,以指定標題添加到我的 「直播」 列表在以Javascript添加的錨鏈接上使用事件處理程序

$("#search").click(function(event){ event.preventDefault(); 
    var show = $("#showTitle").val().toLowerCase(); 
    console.log("the show title is " + show); 
    var url = "https://api.themoviedb.org/3/search/movie?query=" + encodeURIComponent(show)+ "&api_key=9b97ec8f92587c3e9a6a21e280bceba5"; 
    console.log(url); 

     $.ajax ({ 
      url: url, 
       dataType: "json", 
       success: function (data) { 
        // console.log(data.results); 
        var htmlStr = ''; 
         $.each(data.results, function(i, results){ 
          htmlStr += '<a href="#" class="addCurrentlyWatching">' + 'Add' + '</a> <h2 class="movie-title">' + results.original_title + '</h2>' + "Average Rating " + results.vote_average + '<br>' + '<p class="showDescription">' + results.overview + '</p>' + '<br />' + '<img src=https://image.tmdb.org/t/p/w185' + results.poster_path + '>'; 
         }); 
         // console.log(htmlStr); 
         $('#searchresults').html(htmlStr); 
      } 

      // updateCount(); - count the classes inside the "currentywatching" function 

     }); //close .ajax  
    }); 

    $('.addCurrentlyWatching').on('click', function(e){ 
     e.preventDefault(); 
     var movieTitle = $('.movie-title').text(); 
     // console.log(movieTitle); 
     $('.currently-watching').append('<li>' + movieTitle + '</li>'); 
    }); 


    <section id = "shelf1"> 
     <h2> Currently Watching </h2> 
      <ul class="currently-watching"></ul> 
      <div class="number"> 
       <p> You currently have <span id="count"> 0 </span> shows in this list. </p> 

      </div> 

    </section> 

回答

0

使用

$('body').on('click','.addCurrentlyWatching', function(e){ 

看看Event binding on dynamically created elements?

<a href="#" class="addCurrentlyWatching">' + 'Add' + '</a> 

如果你有添加變量定義使用

​​

,如果你不

<a href="#" class="addCurrentlyWatching">Add</a> 

,你可以使用

var movieTitle = $(this).next('.movie-title').text(); 

,而不是

var movieTitle = $('.movie-title').text(); 
相關問題