簡體   English   中英

試圖讓我的按鈕更改文本而無需用戶交互javascript

[英]trying to get my button to change text without user interaction javascript

我做了一個按鈕功能,其中有一個帶有單詞的按鈕,當單擊它時,定義就會顯示出來。 但是現在我正在嘗試使按鈕通過“ 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> 

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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM