简体   繁体   中英

How to change variables within the same function. Javascript

I want to change an input value by clicking on a div + adding a CSS effect . The issue is that I got 10 divs. I can do it by making a function for each one of them but i´m pretty sure that there is a much better way to do it without repeating the code . I´m starting at this, so it would be great if i could get some help.

I got an input and a few divs with just numbers:

 <input type="text" id="screen" dir="rtl"/>
 <div class="key" id="tres">3</div>
 <div class="key" id="dos">2</div>
 <div class="key" id="uno">1</div>
 ...

And then the function:

var screen = document.getElementById("screen");
var tres = document.getElementById("tres");
var dos = document.getElementById("dos");
var uno = document.getElementById("uno");

uno.onclick=function to () {
    screen.value+=uno.innerHTML;
    uno.style.boxShadow="none";
    setTimeout(function() {
        uno.style.boxShadow="0px 0px 5px 2px rgba(0, 0, 0, 0.2), inset 0px 0px 1px 1px rgba(0, 0, 0, 0.2)";
    }, 220);
}

Now what i want to do is to use the same ".onclick" function on every single div , not in my newbie way (re writting the function and changing variables) but in a practical one. I've been trying with "classname" instead of "id". I´ve attempted with ".replace" by trying to replace the value names. And actually im trying with something like this:

 var hell=["uno","dos","tres"];
    var screen = document.getElementById("screen");
    for (var i = 0; i < hell.length; i++) {
        document.getElementById(hell[i]).onclick=function to() {
            screen.value+=document.getElementById(hell[i]).innerHTML;
        }
    }

I barely know what I´m doing so a little bit of enlightenment would be grateful (avoiding jQuery if possible).

Thanks a lot! (Sorry about my bad English)

You can simply select the elements by class name, attach an eventListener to each of the elements, and you'll get what you wanted.

 var screen = document.getElementById("screen"); var elements = Array.from(document.getElementsByClassName('key')); elements.forEach(el => el.addEventListener('click', fn)); function fn(e) { screen.value = (parseInt(screen.value, 10) || 0) + parseInt(e.target.innerText, 10); elements.forEach(el => el.style.boxShadow = "none"); setTimeout(function() { e.target.style.boxShadow = "0px 0px 5px 2px rgba(0, 0, 0, 0.2), inset 0px 0px 1px 1px rgba(0, 0, 0, 0.2)"; }, 220); } 
 <input type="text" id="screen" dir="rtl" /> <div class="key" id="tres">3</div> <div class="key" id="dos">2</div> <div class="key" id="uno">1</div> 

I think what you're looking for is querySelectorAll . Basically, instead of getting each one by ID, you can get all of them in an array by getting them by their class (since they all have the same class).

var myInput = document.getElementById('screen');
var inputs = document.querySelectorAll('.key');

inputs.forEach(function(input) {
  input.onclick = function() {
    myInput.value += input.innerHTML;
    // everything else goes here
  }
});

See this pen for a working example.

ES6

Here is a more optimal solution to your problem. It may seem a bit obscure if you don't know new ES6 syntax, but since you want to learn anyway, here it goes:

 let screenValue = 0, lastClickedDiv; const screen = document.getElementById('screen'), keys = [...document.getElementsByClassName('key')]; const toggleBoxShadow = (clickedDiv) => { if (clickedDiv !== lastClickedDiv) { clickedDiv.classList.add('active'); if (lastClickedDiv !== undefined) { lastClickedDiv.classList.remove('active'); } lastClickedDiv = clickedDiv; } }; const keysClickListener = (event) => { screenValue += parseInt(event.target.textContent); screen.value = screenValue; setTimeout(() => toggleBoxShadow(event.target), 220); }; keys.forEach(key => key.addEventListener('click', keysClickListener)); 
 .key.active { box-shadow: 0 0 5px 2px rgba(0, 0, 0, 0.2), inset 0 0 1px 1px rgba(0, 0, 0, 0.2); } 
 <input type="text" id="screen" dir="rtl"/> <div class="key">3</div> <div class="key">2</div> <div class="key">1</div> 

  • [...document.getElementsByClassName('key')] gets all elements with class name key and turns that collection into an array using spread operator .
  • keys.forEach(key => key.addEventListener('click', keysClickListener)) adds click listener named keysClickListener to each element of keys array.
  • keysClickListener function updates screenValue counter by adding number from clicked div to value it already stores and sets that as #screen 's value. Then it invokes toggleBoxShadow() after 220 ms.

If you want anything else explained, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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