我在这里很费脑筋。
我正在尝试使用 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>
我试图找出这不起作用的原因,但未能找到明确的答案。
最佳答案
this
指的是 DOM 对象。 .data()
仅适用于 jQuery 对象,因此请使用美元符号函数重新包装您的对象:
$(this).data('artist');
或更简洁地说:
$('audio').before(function() {
return $('<div />', {
text: $(this).data('artist')
});
});
关于jquery - 对象 #<HTMLAudioElement> 没有方法 'data',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14793861/