为什么我的"点击"事件监听器为我的删除按钮工作?

时间:2016-02-07 06:02:13

标签: javascript jquery html

所以我正在尝试使用删除类创建一个我的按钮(它是通过我的javascript上的34创建的。)所以我设置了一个onclick,就像我为提交按钮做的那样单击它时没有任何反应。它有一个简单的控制台日志来测试它是否正常工作。我的代码出了什么问题?

$(document).ready(function() {
    $('#movie-search-submit').on('click', function(e) {
        e.preventDefault();
        var search_term = encodeURIComponent($('#movie-title-search').val()); //gets value from element
        var select_media = encodeURIComponent($('#media-select').val());
        console.log(search_term);
        console.log(select_media);
        var url = 'https://itunes.apple.com/search?country=US&term=' + search_term + '&media=' + select_media;


        var log_response = function(response) {
            $.each(response.results, function(key, item) {

                if (item.longDescription !== undefined) {
                    populate_listings(key, item);
                }

            });
        }


        $('.delete').on('click', function(e) {
             e.preventDefault();
             console.log("test");
         });


        var populate_listings = function(key, item) {
            var result_row = '<div id="result-' + key + '" class="row"></div>';
            $('#page-container').append(result_row);
            var title = '<div class="api-result col-md-2 title"><h2>' + item.trackName + '</h2></div>'
            var year = '<div class ="api-result col-md-4 year"><h4>' + item.releaseDate + '</h4></div>'
            var description = '<div class ="api-result col-md-4 description"><p>' + item.longDescription + '</p></div>'
            var delete_button =  '<div class="btn btn-lg btn-primary col-md-2 delete">Delete</div>';
            $('#result-' + key).append(title);
            $('#result-' + key).append(year);
            $('#result-' + key).append(description);
            $('#result-' + key).append(delete_button);

        }

        $.ajax({
            method: "GET",
            url: url,
            dataType: 'jsonp',
            success: log_response,
        });
    });   
});

1 个答案:

答案 0 :(得分:5)

将事件附加到该按钮时,

.delete按钮不可用。所以委托事件

$('body').on('click','.delete', function(e) {
             e.preventDefault();
             console.log("test");
         });