【问题标题】:Why doesn't my jQuery return the value of my equation?为什么我的 jQuery 不返回我的方程的值?
【发布时间】:2016-11-02 01:07:40
【问题描述】:

我创建了一个简单的输入框,用户可以在其中输入一个简单的方程式(无变量)

例如,用户会输入

(5+6) * 7 -2

当用户点击“计算”按钮时,它会触发 jQuery,该 jQuery 使用 .toString() 转换输入,进而求解方程,然后将值放入元素中。

我比较新,所以如果我犯了非常严重的错误,我深表歉意。我希望我已经正确解释了这一点。

这里是 HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Interview exercise</title>
    <script type="text/javascript" src="test.js"></script>
</head>
<body>
    <input name = "equation"/> = <span id="answer"/>
    <br/>
    <button>Calculate</button>
</body>
</html>

这里是 JavaScript/jQuery

$(document).ready(function() {
    $('button').click(function() {
        var answer = $("input[name=equation]").toString();
        $('#answer') = answer;
    });
});

【问题讨论】:

  • 字符串不是数学运算。您必须解析字符串并基本上实现您自己的计算器。
  • 为了您的理智,我建议您先学习 JavaScript,然后再使用 jQuery 并让 StackOverflow 握住您的手
  • .toString() 将值转换为字符串。正如方法名称显然所说。要对多个输入执行数学计算,您必须分别捕获这些数字。然后执行你自己的某种计算......确保你处理整数或浮点数,而不是字符串。
  • @DanielA.White - eval() 对于这个特定目的不安全吗?它只会用于刚刚在当前会话中输入的值,该值不会存储在任何地方,也不会在其他用户的设备上进行评估。 (当然,实际上解析输入的字符串而不仅仅是evaling,如果用户输入了无效的内容,它将允许优雅的错误处理。)
  • @DanielA.White - 他们可以通过浏览器的控制台做哪些他们无法做到的“任何事情”?再次注意,用户在这种情况下可以做的“任何事情”都不会影响其他用户。

标签: javascript jquery html tostring


【解决方案1】:

我不知道 JavaScript eval() 函数。
非常感谢@nnnnnn 和@DanielA.White 之间的争论!

关于eval() 不安全
这是另一个SO answer to explain the risks,在你的情况下,它是不存在的。

所以这里是你的 HTML 的计算函数:

$(document).ready(function(){
    $('button').click(function(){
        var answer = eval( $("input[name='equation']").val() );
        $('#answer').html(answer);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input name="equation" value="(5+6) * 7 -2"> = <span id="answer"></span>
<br>
<button>Calculate</button>




编辑
为了使.val() 函数更安全...
但主要是为了防止不可能的计算,这里有一个更新!

这个加长的脚本过滤了来自键盘的“允许的键”。

但是,如果输入了不可能的计算,例如4//(68+()
它输出:«你的方程式有问题。»

$(document).ready(function(){
    var allowedKeys=[48,49,50,51,52,53,54,55,56,57, // 0 to 9 (keyboard)
                     96,97,98,99,100,101,102,103,104,105, // 0 to 9 (numpad)
                     111,106,109,107,110,    // characters / * - + . (numpad)
                     189,190,8,32,13    // character - . [backspace] [space] [enter] (keyboard)
                    ];
    var allowedShiftKeys=[51,56,57,48,187,57,48,16];  // characters / * + ( ) [shift] (keyboard + shift)

    $("input[name='equation']").on("keydown",function(e){
        // Clear previous answer
        $('#answer').html("");

        // Check for allowed keydown
        if( ($.inArray( e.which,allowedKeys) != -1 && !e.shiftKey) || ($.inArray(e.which,allowedShiftKeys)!=-1 && e.shiftKey) ){
            console.log("Allowed key.");
        }else{
            // Don't print the key in the input field.
            console.log("Disllowed key.");
            e.preventDefault();

            // Helper to find key number
            console.log(e.which);
        }

        // [enter] handler to simulate a button click.
        if(e.which==13){
            $('button').click();
        }
    });

    $('button').click(function(){
        var InputtedValue = $("input[name='equation']").val();
        
        // Remove "//" sequence... Which has the special meaning of a "comment start".
        // Has to be removed before eval() works.
        for(i=0;i<InputtedValue.length;i++){
            var position = InputtedValue.indexOf("//");
            if(position!=-1){
                console.log('Removing "//" occurance.');
                InputtedValue = InputtedValue.replace("//","/");
                // Redo the loop from start.
                i=0;
                $("input[name='equation']").val(InputtedValue);
            }
        }

        // Try the eval() function... And catch the error if any (Error will come from the inputted formula).
        // Prevents the script from just jamming here.
        try{
            var answer = eval( InputtedValue );
        }
        catch(error){
            console.log("ERROR: "+error.message);
        }

        // If there is an answer.
        if(typeof(answer)==="number"){
            $('#answer').html(answer);
        }else{
            $('#answer').html("Something is wrong in your equation.");
        }
        console.log("Answer: "+answer);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="equation" value="(5+6) * 7 -2"> = <span id="answer"></span>
<br>
<button>Calculate</button>

【讨论】:

  • 如果用户不输入括号,有没有办法按照操作顺序运行?
  • 我现在正在处理括号问题...但不是这个问题。如果缺少括号,则 eval 失败并且脚本中止。现在,如果根本没有括号是另一回事!我没有注意到 eval() 没有正确“评估”它......会检查我能做什么,但我会先发布我的实际改进(几分钟后)。
  • 嗯。从我刚刚进行的第一个测试中,eval() 确实在没有括号的情况下正确说明了操作顺序。
  • 我刚刚发布了我的编辑...希望你会喜欢!编码很有趣;)
猜你喜欢
  • 2011-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 2020-08-06
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多