简体   繁体   English

运行两个不同的javascript函数onclick

[英]Run two different javascript functions onclick

I have two javascript functions and I want them both to run when I press a button. 我有两个JavaScript函数,我希望它们都可以在我按下按钮时同时运行。 I have tried different things but only one would work and not the other. 我尝试了不同的方法,但是只有一种方法可以工作,而另一种则不能。 I ran the function startTimer onclick on the button but don't know how to run the first one where the text is displayed. 我在按钮上单击时运行了startTimer函数,但不知道如何运行第一个显示文本的位置。

JS: JS:

$(function () {
  count = 0;
  wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5"];
  setInterval(function () {
    count++;
    $(".questions1").fadeOut(400, function () {
      $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
    });
  }, 8000);
});


     function displayNextImage() {
              x = (x === images.length - 1) ? 0 : x + 1;
              document.getElementById("img").src = images[x];
          }

          function displayPreviousImage() {
              x = (x <= 0) ? images.length - 1 : x - 1;
              document.getElementById("img").src = images[x];
          }

          function startTimer() {
              setInterval(displayNextImage, 8000);
          }

          var images = [], x = -1;
          images[0] = "img/question-2.png";
          images[1] = "img/question-3.png";
          images[2] = "img/question-4.png";
          images[3] = "img/question-5.png";
          images[4] = "img/question-6.png";

HTML 的HTML

<img id="img" src="img/question-1.png" alt="">
<h1 class="questions1">Text 1</h1>

<button id="begin" onclick = "startTimer()">Begin</button>

You should trigger this button via jQuery rather than using an onclick attribute in HTML. 您应该通过jQuery而不是在HTML中使用onclick属性来触发此按钮。

For example you could do this: 例如,您可以这样做:

$('#begin').on('click', function(){
  firstFunction();
  secondFunction();
});

And you would have both functions executed when you click the button. 当您单击按钮时,将同时执行这两个功能。

You need a function to manage what exactly you want to happen onclick. 您需要一个函数来管理您希望onclick发生的确切事件。 I would create a wrapper function to call the two functions. 我将创建一个包装器函数来调用这两个函数。

    function onClickWrapper(){ 
       //Do onclick stuff 
       startTimer(); 
       otherFunction();
    }

Then just modify your HTML: 然后只需修改您的HTML:

<img id="img" src="img/question-1.png" alt="">
<h1 class="questions1">Text 1</h1>

<button id="begin" onclick = "onClickWrapper()">Begin</button>

You can just call the two functions you want from within the click handler, like this: 您可以从点击处理程序中调用所需的两个函数,如下所示:

function onClick(){
    startTimer();
    otherFunction();
}

You may want to think about function names some more, but that's the general structure. 您可能需要考虑更多函数名称,但这是常规结构。

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

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