1

我在这里有很多脑筋急转弯。

我正在尝试使用 jQuery 在 html5 音频标签上方添加有关歌曲的数据。我想出了一种可以更自动化地做到这一点的方法是将 data-* 属性添加到音频标签,但是当我尝试使用 jQuery 将它们拉回时出现错误:“Object # has no method 'data'”。

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
         <audio controls data-artist="horse">
              <source src="horse.ogg" type="audio/ogg">
              <source src="horse.mp3" type="audio/mpeg">
              <a href="horse.mp3">horse</a>
        </audio>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script>
            $(function(){
                $('audio').before(function(){
                    artist = $('<div>');
                    artist.html(this.data('artist'));
                    return artist;
                });
            });
        </script>
    </body>
</html>

我试图找到一个不起作用的原因,但未能找到明确的答案。

4

2 回答 2

3

this指的是 DOM 对象。.data()仅在 jQuery 对象上可用,因此使用美元符号函数重新包装您的对象:

$(this).data('artist');

或更简洁地说:

$('audio').before(function() {
    return $('<div />', {
        text: $(this).data('artist')
    });
});
于 2013-02-10T01:57:39.560 回答
1

你首先必须this用 jQuery 包装:

artist.html( $(this).data('artist') );

或者,您可以使用原生 HTML5 列表(在 IE < 9 中不起作用):

artist.html( this.dataset.artist );
于 2013-02-10T01:57:32.223 回答