2014-09-22 52 views
0

我在處理onclick事件時遇到了麻煩。 我的HTML:內聯onclick函數(這個)不調用jQuery方法

<div> 
    <button onclick="sound(this)">Listen</button> 
    <audio class="audio" src="example.mp3"></audio> 
</div> 

我的JS(jQuery的):

function sound(element){ 
    $audio = element.siblings('.audio').first(); 
    $audio.trigger('play'); 
} 

的事情是不是播放的音頻文件。 我也做了一些測試。

function sound(element){ 
    alert(element.tagName); -> it worked 
    alert(element.parent().tagName); -> not worked and so on with siblings() or next() 

東西一定是錯的。請幫助我。非常感謝。

+2

'element'(了'this'您傳遞)是土生土長的DOM元素,而不是一個jQuery的包裝! – Bergi 2014-09-22 11:34:39

回答

1

而不是

function sound(element){ 
    $audio = element.siblings('.audio').first(); 
    $audio.trigger('play'); 
} 

試試這個

function sound(element){ 
    $audio = $(element).siblings('.audio').first(); //here 'element' is just a DOM element you have to wrap 'element' in jquery wrapper. 
    $audio.trigger('play'); 
} 
+0

這將是很好的提及'onclick =「」'是過時的方式來添加事件處理程序。 – Regent 2014-09-22 11:37:22

+0

非常感謝,它的工作。 – 2014-09-22 11:49:43

+0

@ Taiguguen ..你的歡迎.. !!! – 2014-09-22 11:50:02