简体   繁体   中英

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.

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. Any help is greatly appreciated.

The following is the HTML generated, which I found with Firefox's 'inspect element':

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

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

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

You need to get the DOM node from the jQueryObject:

$(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).prev('.pipe1');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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