0

我曾经使用 .live 但我现在尝试用更好的 .on 替换那些,但我似乎不理解 API 说明,因为下面的代码什么都不做,我应该收到警报。谁能看到我在哪里搞砸了?

<!DOCTYPE html>
<html>
    <head>
        <title>Online Media Player</title>
        <link rel="stylesheet" href="/assets/css/music-player.css" type="text/css" media="screen" charset="utf-8">

        <script src="/assets/js/jquery-1.8.3.js"></script>
    </head>

    <body>
        <div class="main-center">
            <h1>Please select your choice of music</h1>
            <a class="openplayer" data-genre="rock" href="#">Rock</a>
            <a class="openplayer"  data-genre="hip" href="#">Hip Hop</a>
            <a class="openplayer"  data-genre="country" href="#">Country</a>
            <a class="openplayer"  data-genre="featured" href="#">Featured Artist</a>
        </div> <!-- /.main-center -->

        <script type="text/javascript">
            (function($) {
                $('.openplayer').on('click', 'a', function(e){
                    var genre = $(this).data('genre');
                    e.preventDefault();
                    alert(genre);
                });
            })(jQuery);
        </script>
    </body>
</html>
4

1 回答 1

5

您应该调用on元素的容器并将要附加到的元素的选择器传递给它。您现有的代码on不是在容器上调用,而是在链接本身上调用。尝试:

$('.main-center').on('click', '.openplayer', function(e) {
    var genre = $(this).data('genre');
    e.preventDefault();
    alert(genre);
});
于 2013-03-31T04:31:17.450 回答