0

我正在尝试创建一个小提琴,它可以让我通过更改图形并输入显示在图形下方的文本。我正在为此使用 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]);

我如何使它工作?

4

1 回答 1

2

这是一个 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 语法。这意味着,Math.sin(x)用户可能只是输入sin(x). 此外,还有幂运算符,即可以键入^来代替。Math.pow(x,2)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 代码作为输入,这很容易发生。

于 2016-10-04T11:42:01.003 回答