javascript - 更改文本框中的函数不会更改图形

标签 javascript jsxgraph

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

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

上面是当您更改图形中显示的文本中的函数时有效的示例也会更改。

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

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]);

如何让它发挥作用?

最佳答案

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

关于javascript - 更改文本框中的函数不会更改图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39761153/

相关文章:

javascript - 子字符串和第一个点之间的文本

javascript - 构造函数中定义的属性是自己的还是继承的?

javascript - JSXGraph 性能问题

javascript - JSXGraph 中的可拖动曲线

javascript - 如何从 Spring 客户端应用程序更新 Service Worker 中的语言

javascript - 提交跨域ajax POST请求

javascript - jQuery 实时悬停

javascript - JSXGraph - 交叉点和从交叉点创建的多边形

javascript - 两个板共享相同的 slider (jsxGraph),可能吗?

javascript - 在 JSXGraph 中绘制一条与直线相切的无差异曲线