在Javascript中添加的锚链接上使用事件处理程序

时间:2015-12-03 00:12:41

标签: javascript jquery ajax

我有一个Ajax调用,它返回一组电影标题。我想点击每个标题旁边的按钮,然后将标题添加到"当前正在观看"名单。我的#34;添加"链接似乎没有接受事件处理程序。我该怎么做才能将指定的标题添加到我的"目前正在观看"列表

$("#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>

3 个答案:

答案 0 :(得分: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> 

如果你不

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

你可以使用

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

而不是

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

答案 1 :(得分:0)

解决方案:

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

如果您对更详细的答案感兴趣:

Explanation

答案 2 :(得分:0)

对于旧版本的jQuery,请使用$ .live&amp; $ .delegate

文件:

http://api.jquery.com/live/

http://api.jquery.com/delegate/