【问题标题】:Changing the function in the text box is not changing the graph更改文本框中的函数不会更改图形
【发布时间】:2016-09-29 03:58:01
【问题描述】:

我正在尝试创建一个小提琴,它可以让我更改图形并输入显示在图形下方的文本。我正在为此使用 jsxgraph 库。

http://jsxgraph.uni-bayreuth.de/wiki/index.php/Change_Equation_of_a_Graph#JavaScript_Part

上面是一个例子,当你改变显示的文本中的函数时,图表也会改变。

我正在尝试使用小提琴的相同示例。但它不起作用。

https://jsfiddle.net/me55dw4h/30/

初始代码:

board = JXG.JSXGraph.initBoard('box', {boundingbox: [-6, 12, 8, -6], axis: true});
eval("function f(x){ return "+document.getElementById("eingabe").value+";}");
graph = board.create('functiongraph', [function(x){ return f(x); },-10, 10]);

如何让它发挥作用?

【问题讨论】:

    标签: javascript jsxgraph


    【解决方案1】:

    这是一个 jsfiddle 特有的问题。如果函数doIt的声明改为

    doIt = function (){
      //redefine function f according to the current text field value
      eval("function f(x){ return "+document.getElementById("eingabe").value+";}");
      //change the Y attribute of the graph to the new function 
      graph.Y = function(x){ return f(x); };
      //update the graph
      graph.updateCurve();
      //update the whole board
      board.update();
    };
    

    而不是

    function doIt() {
         ...
    }
    

    然后示例运行。

    但让我强调一下,同时 JSXGraph 带有它自己的解析器 JessieCode(参见 https://github.com/jsxgraph/JessieCode),它允许输入常见的数学语法而不是 JavaScript 语法。这意味着,用户可以输入sin(x),而不是Math.sin(x)。此外,还有电源运算符^,即可以键入x^2,而不是Math.pow(x,2)

    使用 JessieCode 进行函数绘图的最小示例如下所示,请参阅 https://jsfiddle.net/eLs83cs6/

    board = JXG.JSXGraph.initBoard('box', {boundingbox: [-6, 12, 8, -6], axis: true});
    
    doPlot = function() {
        var txtraw = document.getElementById('input').value, // Read user input
            f = board.jc.snippet(txtraw, true, 'x', true), // Parse input with JessieCode
            curve;
    
        board.removeObject('f'); // Remove element with name f
        curve = board.create('functiongraph', [f, -10, 10], {name:'f'});
    };
    
    doPlot();
    

    另一个副作用是,使用 JessieCode 解析数学语法可以防止 XSS 攻击,如果允许用户提供任意 JavaScript 代码作为输入,这很容易发生。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多