2021年1月18日星期一

How would you write this jQuery code that binds a clicked element to functions in JavaScript?

I have being trying to solve a problem of how to bind a clicked element to functions using JavaScript, and after many days finally found a solution here provided by @JerdineSabio. My original problem was asked at Stackoverflow and it had to do with a single JavaScript script handling many buttons and performing speech recognition. The code that binds the clicked button to the functions is written in jQuery and involves using function(e) . The jQuery statement takes 3 parameters, but in JS the equivalent expression only takes two (the event (eg. the clicking) and the function). I've looked up the usual references I depend upon but haven't found a way to write it in Javascript. I have solved the scripting problem; so I just want to find an answer to this question in case I might want to use JS only in the future, as I tend to rely on JS more than jQuery, and I also read about function(e) before and watched a video on Youtube about it, but I still did not quite understand what "e" is and what it does.
The jQuery script below works as it should. The code changes the color of the button that's next to it. Once again, this involves multiple buttons but there is only one script for them all.

I have tried:

document.addEventListener("click", myFunction);   function myFunction(e) {  this.previousElementSibling.setAttribute("style", "background-color: gold") ...  ....};  

and I've tried a few more things, but I can't make the function work correctly no matter what I try.

The HTML is:

 <div class="container">    <button id="first" type="button" class="btn btn-danger"></button>    <button id="first" type="button" class="btn btn-warning"></button>    </div>  

The jQuery is:

 $(document).ready(function(){       $(document).on("click", "#first", function(e) {          $(this).siblings().css("background-color", "gold");          });    });   
https://stackoverflow.com/questions/65775269/how-would-you-write-this-jquery-code-that-binds-a-clicked-element-to-functions-i January 18, 2021 at 09:16PM

没有评论:

发表评论