更改文本框中的功能不会改变图
问题描述:
我正在尝试创建一个小提琴,它可以让我更改图形,并在图形下方显示输入的文本。我正在使用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]);
我如何工作的呢?
答
这是一个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)
。此外,还有电力运营商^
,即代替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解析防止跨站脚本攻击这将是容易如果允许用户提供任意JavaScript代码作为输入,则可能。