この質問は愚かなように見えるかもしれませんが、問題の内容がわかりません。当初、私はページにオーディオを追加します。この機能でのみ.jsファイルを持っている:このコードは別のファイルでは動作しますが、インラインでは動作しません
function addAudio(id_name, audio_filepath) {
var audio = $('<audio />')
.prop('id', 'audio' + id_name)
.prop('src', audio_filepath)
.text("Your reader doesn't support audio.");
$('body').append(audio);
$('#' + id_name).click(function() {
audio.get(0).play();
});
}
そしてそれは、このようにHTMLで呼ばれています:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<!-- some content here -->
<button id="test">Play</button>
<!-- reference to lib containing jquery -->
<script type="text/javascript" src="js/lib.min.js"></script>
<!-- script where the function addAudio resides -->
<script type="text/javascript" src="js/add-audio.js"></script>
<script type="text/javascript">
$().ready(function() {
addAudio('test', 'audio/01-test.wav');
});
</script>
</body>
</html>
そして、それが正常に動作します。問題は、ファイルから関数を移動してスクリプトタグにインラインで入れようとするときです。その場合、ボタンをクリックすると、コンソールにUncaught TypeError: Cannot read property 'play' of undefined
が表示されます。
これは修正されたコードである:誤りを分離しようと
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<!-- some content here -->
<button id="test">Play</button>
<!-- reference to lib containing jquery -->
<script type="text/javascript" src="js/lib.min.js"></script>
<script type="text/javascript">
function addAudio(id_name, audio_filepath) {
var audio = $('<audio />')
.prop('id', 'audio' + id_name)
.prop('src', audio_filepath)
.text("Your reader doesn't support audio.");
$('body').append(audio);
$('#' + id_name).click(function() {
audio.get(0).play();
});
}
$().ready(function() {
addAudio('test', 'audio/01-test.wav');
});
</script>
</body>
</html>
、私は機能が.jsファイルである場合、変数audio
はjQueryオブジェクト[audio#audiotest]
であることが判明、しかし場合関数その変数はオブジェクトn.fn.init {}
です。
どうしてですか?
EDIT
私はそれが(私はEPUB3形式の電子ブックを作ってるんだ)XHTMLファイルにありますので、それが起こることに気付きました。ファイルをhtmlに変更すると、再び動作します。しかし、オーディオタグはxhtmlでサポートされています(ここで仕様を確認することができます:http://www.idpf.org/accessibility/guidelines/content/xhtml/audio.php)ので、私が言ったように、機能が別のファイルにあれば動作します。なぜインラインではないのですか?
にライン
$('<audio />')
を変更し、問題を解決しましたか? –コードが別のファイルにあるとき、オーディオは正常に再生されます。コードがインラインである場合、コンソールは 'Uncaught TypeError:未定義の 'play'プロパティを読み取れません。 ' –
' 'にあります... – IMTheNachoMan