这是一个 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 代码作为输入,这很容易发生。