内联onclick函数(this)不调用jQuery方法

inline onclick function(this) not calling jQuery methods

本文关键字:调用 jQuery 方法 this onclick 函数 内联      更新时间:2023-09-26

我在处理onclick事件时遇到了麻烦。我的HTML:

<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()

一定出了什么问题。请帮帮我。非常感谢。

而不是

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');
}