如何在jquery的while循环中调用点击函数?

问题描述 投票:0回答:1

如何在jquery中的while循环中调用点击函数?

$(document).ready(function(){
  var count=2;
  while(count>0){
    $(".box1").click();
    count--;
   }
   $(".box1").click(function(){
     var aud=document.createElement('audio');
     aud.src="tom-1.mp3";
     aud.play();
   });    
});
javascript jquery loops button click
1个回答
2
投票
  1. 你需要指定 .box1 作为 String.
  2. 附上 event handler 在调用它之前。
  3. 添加 audio 到HTML。(不要在javascript中虚拟使用),否则你会得到 Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. . now I am getting this error. 错。

$(document).ready(function() {
  var count = 2;

  $(".box1").click(function() {
    var aud = document.getElementById('audio');
    // replace with your audio
    aud.src = "https://freesound.org/data/previews/515/515391_1453392-lq.mp3";
    aud.play();
  });

  while (count > 0) {
    $(".box1").click();
    count--;
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio id='audio'></audio>
<button class='box1'>Play</button>
© www.soinside.com 2019 - 2024. All rights reserved.