2013-02-10 2 views
1

저는 여기에 꽤 두뇌의 scratcher가 있습니다.Object # <HTMLAudioElement>에는 'data'메소드가 없습니다.

jQuery를 사용하여 html5 오디오 태그 위의 노래에 대한 데이터를 추가하려고합니다. 내가 더 자동화 할 수있는 방법은 오디오 태그에 data- * 속성을 추가하는 것이지만, jQuery를 사용하여 데이터를 꺼내려고하면 "Object #에는 데이터가 없습니다."라는 오류가 발생합니다.

<!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> 

이 방법이 작동하지 않는 이유를 찾으려고했지만 확실한 답을 찾을 수 없었습니다.

답변

3

this은 DOM 개체를 참조합니다. .data() jQuery를 객체에서만 사용할 수 있습니다, 그래서 달러 기호 기능 개체를 다시 포장 : 더 간결

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

을 또는 :

$('audio').before(function() { 
    return $('<div />', { 
     text: $(this).data('artist') 
    }); 
}); 
+0

감사를 설명, 나는 .data()가 jQuery에게 DOM 객체를보고 데이터 태그를 가져다 줄 것이라고 생각했지만 데이터 태그를 이전에 가져온 것처럼 보였다. –

1

먼저 jQuery를에 this 포장해야합니다 :

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

을 다른 방법으로, (IE < 9 작동하지 않습니다) 기본 HTML5 목록 사용할 수 있습니다

artist.html(this.dataset.artist); 
+0

흠 ... 그래/마른 세수 –

관련 문제