简体   繁体   English

使用Jquery的.closest访问音频元素不起作用?

[英]Using Jquery's .closest to access audio element not working?

I used .each() and before() to automatically insert an audio element with class 'pipe1' for a hover effect before every element of class 'product_name' because an individual audio element cannot overlap itself, thus each button needs its own sound effect. 我使用.each()before()自动在类'product_name'每个元素之前插入具有'pipe1'类的音频元素,以实现悬停效果,因为单个音频元素自身不能重叠,因此每个按钮都需要自己的声音效果。

I know the insert worked, because when I inspect the page I see the element. 我知道插入有效,因为当我检查页面时会看到该元素。 The element played when being accessed directly, but now using .closest() it isn't working. 元素在直接访问时播放,但是现在使用.closest()时不起作用。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

The following is the HTML generated, which I found with Firefox's 'inspect element': 以下是生成的HTML,是通过Firefox的“检查元素”发现的:

<audio class="pipe1">
  <source src="/frontshift/audio/pipe1.mp3"></source>
  <source src="/frontshift/audio/pipe1.ogg"></source>
</audio>
<span class="product_name">Product</span>

All of the code I'm working with is activated in the same .hover effect, which is $(".product_name").hover() 我正在使用的所有代码都以相同的.hover效果激活,即$(".product_name").hover()

The following code successfully plays the audio: 以下代码成功播放了音频:

$(".pipe1")[0].currentTime = .04;
$(".pipe1")[0].play();

The following code does NOT: 以下代码不支持:

$(this).closest(".pipe1").currentTime = .04;
$(this).closest(".pipe1").play();

The following alert turns up undefined: 以下警报显示为未定义:

alert($(this).closest(".pipe1").attr("class"));

.closest() selects ancestors, to select previous sibling use .prev() .closest()选择祖先,使用.prev()选择先前的同级

var audio = $(this).prev(".pipe1")[0];
audio.currentTime = .04;
audio.play();

You need to get the DOM node from the jQueryObject: 您需要从jQueryObject获取DOM节点:

$(this).closest(".pipe1").get(0).currentTime = 0.4

Or using Array like behavior: 或使用类似数组的行为:

$(this).closest(".pipe1")[0].currentTime = 0.4

Are you sure that the context ( this ) refers to an element inside the audio tag? 您确定上下文( this )引用了音频标签中的元素吗?

是的,您应该使用$(this).prev('.pipe1');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM