试图让我的按钮更改文本而无需用户交互javascript

时间:2018-11-22 18:57:07

标签: javascript html arrays html5

我创建了一个按钮功能,该按钮功能带有一个带有单词的按钮,当单击该按钮时,将显示定义。但是现在我正在尝试使按钮通过“ SetInterval”每隔几秒钟显示一次定义,而无需单击,而且我不知道该怎么做,请您帮忙。

'use strict';
//below is the function for the even
$(document).ready(function() {
  //
  function salutationsHandler(evnt) {
    let box = $("#message-box");

    if (box.hasClass("hidden")) {
      box.attr("class", "");
      $(evnt.target).text("1.Salutation");
    } else {
      box.attr("class", "hidden");
      $(evnt.target).text('a greeting in words or actions');


    }

  }
  //end of function
  setInterval(salutationsHandler, 1000);

  //start of another
  function DiffidenceHandler(evnt2) {
    let box2 = $("#message-box2");

    if (box2.hasClass("hidden")) {
      box2.attr("class", "");
      $(evnt2.target).text("2.Diffidence");
    } else {
      box2.attr("class", "hidden");
      $(evnt2.target).text("the quality of being shy");
    }
    console.log(evnt2);
  }
  //lets me target id
  let salutationsGrab = $('#Salutations');
  // adds event to said id 
  // event listeners grab events from functions
  salutationsGrab.on('click', salutationsHandler);



  let DiffidenceGrab = $("#Diffidence");

  DiffidenceGrab.on("click", DiffidenceHandler);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>hello welcome to our dictionary</h1>
<h2>Click on button to reveal definition of word shown</h2>


<button id="Salutations">1.Saluation</button>
<div id="message-box"></div>
<br>
<button id="Diffidence">2.Diffidence</button>
<div id="message-box2"></div>
<br>

1 个答案:

答案 0 :(得分:1)

函数salutationsHandler需要事件生成的事件对象才能起作用。您可以使用jQuery的.trigger()来“单击”按钮,而不是直接调用该函数。

function salutationsHandler(evnt) {
  const box = $("#message-box");
  const target = $(evnt.target);

  if (box.hasClass("hidden")) {
    box.removeClass("hidden");
    target.text("1.Salutation");
  } else {
    box.addClass("hidden");
    target.text('a greeting in words or actions');
  }

}

let salutationsGrab = $('#Salutations');
salutationsGrab.on('click', salutationsHandler);

setInterval(() => salutationsGrab.trigger('click'), 1000);
.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>hello welcome to our dictionary</h1>
<h2>Click on button to reveal definition of word shown</h2>


<button id="Salutations">1.Saluation</button>
<div id="message-box">a greeting in words or actions</div>