如何压缩这些jQ函数?

时间:2017-07-03 06:07:37

标签: javascript jquery

//正在处理一些计算器的hw

//我确信有一种更简单的方法,但我不记得怎么做了。

//这就是它,但是这个网站要我在这篇文章中添加更多的文字

// asdfasdfasdfsafs

$(document).ready(function(){
  console.log('jQ is working');


$(".operator1").click(function(){

  var a = document.getElementById('fieldA').value;
  var b = document.getElementById('fieldB').value;
  parseInt(a);
  parseInt(b);
  add = +a + +b;
  $('#answer').append(add);




});

$(".operator2").click(function(){

  var a = document.getElementById('fieldA').value;
  var b = document.getElementById('fieldB').value;
  sub = (a - b);
  $('#answer').append(sub);


});

$(".operator3").click(function(){

  var a = document.getElementById('fieldA').value;
  var b = document.getElementById('fieldB').value;
  mult = a * b;
  $('#answer').append(mult);

});

$("#operator4").click(function(){

  var a = document.getElementById('fieldA').value;
  var b = document.getElementById('fieldB').value;
  console.log(a / b);
  divi = a / b;
  $('divi').appened(divi);

});

function doMath(a, b){

}




});

1 个答案:

答案 0 :(得分:0)

使用某些data属性



$(document).ready(function() {
  console.log('jQ is working');

  $('.operator').click(function() {
    var a = document.getElementById('fieldA').value;
    var b = document.getElementById('fieldB').value;
    a = parseFloat(a);
    b = parseFloat(b);
    var res = eval(a +$(this).attr('data-opr')+b);
  $('#answer').append(':'+res);
  });


  function doMath(a, b) {

  }

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="operator" data-opr="+">+</button>
<button class="operator" data-opr="-">-</button>
<button class="operator" data-opr="*">*</button>
<button class="operator" data-opr="/">/</button>
<input type="number" value="2" id="fieldA">
<input type="number" value="9" id="fieldB">
<p id="answer"><p>
&#13;
&#13;
&#13;