我2天前开始学习JS。 我下载了一个代数计算器并将其插入我的网页。这是完整的代码:
<!doctype html>
<html>
<head>
<div style="width:100%;">
<textarea id="output1" name="terminal" rows="4" cols="80" style="width:100%;"></textarea>
<input name="execute" value="▶" onclick="execute(1);" type="button">
</div>
<script src="javascripts/jquery.min.js"></script>
<script src="dist/latest-stable/algebrite.bundle-for-browser.js"></script>
<script type="text/javascript" language="javascript">
function execute (whichTerminal) {
var sandbox = $('sandbox');
var jsResult = $('jsResult');
try {
var textToBeExecuted = 'factor(3+3)';
var result;
if (/Algebrite\.[a-z]/.test(textToBeExecuted) || /;[ \t]*$/.test(textToBeExecuted)) {
result = eval(textToBeExecuted);
}
else {
result = Algebrite.run(textToBeExecuted);
}
//alert(result);
$('#output' + whichTerminal).val(result)
}
catch (err) {
var errDesc = err;
errorBox.update('<h4>Error!<\/h4><code>' + errDesc + '<\/code>' );
errorBox.show();
}
}
</script>
脚本返回3 + 3或6(var textToBeExecuted = 'factor(3+3)'
)的素数因子,但我需要的是评估从URL中获取的表达式(例如:/?input=3%B54
表示3 + 4并返回7) 。我怎样才能做到这一点?请帮忙!
答案 0 :(得分:0)
//尝试此代码。 URL中的参数需要添加为?expression = 1 + 1 //此外,代码可以根据要求轻松调整。
<!DOCTYPE html>
<html lang = "en">
<body>
<script>
var decodedString = decodeURIComponent(window.location.search.split("expression=")[1]);
console.log(decodedString);
if(decodedString.split('\+').length > 1 && decodedString.split('\+').length < 3){
var exp = decodedString.split('\+');
var result = parseInt(exp[0]) + parseInt(exp[1]);
alert(decodedString + " = " + result);
}
else if(decodedString.split('\-').length > 1 && decodedString.split('\-').length < 3){
var exp = decodedString.split('\-');
var result = parseInt(exp[0]) - parseInt(exp[1]);
alert(decodedString + " = " + result);
}
else if(decodedString.split('\*').length > 1 && decodedString.split('\*').length < 3){
var exp = decodedString.split('\*');
var result = parseInt(exp[0]) * parseInt(exp[1]);
alert(decodedString + " = " + result);
}
else if(decodedString.split('\/').length > 1 && decodedString.split('\/').length < 3){
var exp = decodedString.split('\/');
var result = parseInt(exp[0]) / parseInt(exp[1]);
alert(decodedString + " = " + result);
}
else{
console.log("Not a valid operator (Operator Supported : +-*/) found or more than 1 operator found in expression.");
}
</script>
</body>
</html>