为什么Jquery.globalEval不起作用?

时间:2015-11-26 18:18:46

标签: javascript jquery html5 dom

我正在尝试通过附加在屏幕中单击的跨度值来计算用户定义的等式(基本计算器)。 当我想使用Jquery.GlobalEval进行评估时,似乎没有任何事情发生。

这是我的HTML代码:

<div class="screen"></div>


        <div class="keys">
            <!-- operators and other keys -->
            <span>7</span>
            <span>8</span>
            <span>9</span>
            <span>+</span>
            <span>4</span>
            <span>5</span>
            <span>6</span>
            <span>-</span>
            <span>1</span>
            <span>2</span>
            <span>3</span>
            <span>/</span>
            <span>0</span>
            <span>.</span>
            <span class="eval">=</span>
            <span>x</span>
        </div>
    </div>

这是我的jquery代码:

jQuery(function() {

    // when C is clicked
    $(".clear").click(empty);
    var key;
    //any of the keys is clicked
    $(".keys span").not(".eval").click(function() {

        //======================
        if($(this).not(".eval")) {
            $('.screen').append($(this).html());
        }

        key = $('.screen').text().replace(/x/g, '*').replace('=', '');

    });


    $(".eval").click(function() {
        alert(calculate());
    });

    function empty() {
        $(".screen").empty();
    }
    function calculate() {
        jQuery.globalEval("var result = "+ key + ";");
    }
});

谢谢,

1 个答案:

答案 0 :(得分:1)

您需要返回新变量result。试试这个(结果输出到控制台):

jQuery(function() {

  // when C is clicked
  $(".clear").click(empty);
  var key;
  //any of the keys is clicked
  $(".keys span").not(".eval").click(function() {

    //======================
    if ($(this).not(".eval")) {
      $('.screen').append($(this).html());
    }

    key = $('.screen').text().replace(/x/g, '*').replace('=', '');

  });


  $(".eval").click(function() {
    console.log(calculate());
    alert(calculate());
  });

  function empty() {
    $(".screen").empty();
  }

  function calculate() {
   jQuery.globalEval("var result = " + key + ";");
   return result;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="screen"></div>


<div class="keys">
  <!-- operators and other keys -->
  <span>7</span>
  <span>8</span>
  <span>9</span>
  <span>+</span>
  <span>4</span>
  <span>5</span>
  <span>6</span>
  <span>-</span>
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>/</span>
  <span>0</span>
  <span>.</span>
  <span class="eval">=</span>
  <span>x</span>
</div>
</div>