简体   繁体   中英

Chrome App Input function simplify

I am writing a chrome app for logging a uses time spent on projects, I have a set of push buttons that allow them to just use 4 quick buttons with preset times on each one eg 7.5min , 15min, 1 hour, 4 hour.

This is to encourage users to submit project time as close to real time as possible while making it easier rather than opening a webapp.

This bit of code basically just adds the defined time to the input box "hourTime" using the 4 buttons.

Is there a way for me not to call 4 separate functions for each button and simplify my code? i am not really a JS guru so i am sure i could improve this.

Stackoverflow help would be much appreciated.

//adds 7.5 minutes to the input    
function addbt1(){
  var b1 = ((1/8)+ Number(document.getElementById("hourTime").value));
  b1 = b1.toFixed(3);
  document.getElementById("hourTime").value = b1;
}
document.querySelector("#add1Funct").addEventListener("click", addbt1);
//adds 15 minutes to the input  
function addbt2(){
  var b2 = ((1/4)+ Number(document.getElementById("hourTime").value));
  b2 = b2.toFixed(3);
  document.getElementById("hourTime").value = b2;
}
document.querySelector("#add2Funct").addEventListener("click", addbt2);
//adds 1 hour to the input  
function addbt3(){
  var b3 = ((1)+ Number(document.getElementById("hourTime").value));
  b3 = b3.toFixed(3);
  document.getElementById("hourTime").value = b3;
}
document.querySelector("#add3Funct").addEventListener("click", addbt3);
//adds 4 hour to the input 
function addbt4(){
  var b4 = ((1*4)+ Number(document.getElementById("hourTime").value));
  b4 = b4.toFixed(3);
  document.getElementById("hourTime").value = b4;
}
document.querySelector("#add4Funct").addEventListener("click", addbt4);

Accept argument for the handler-function which can be difference for different elements event is attached on!

 function addbt(val) { //accept argument as `val` document.getElementById("hourTime").value = (val + Number(document.getElementById("hourTime").value)).toFixed(3); } document.querySelector("#add1Funct").addEventListener("click", function() { addbt((1 / 8)); }); document.querySelector("#add2Funct").addEventListener("click", function() { addbt((1 / 4)); }); document.querySelector("#add3Funct").addEventListener("click", function() { addbt((1)); }); document.querySelector("#add4Funct").addEventListener("click", function() { addbt((1 * 4)); }); 

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