背景信息:我试图将距离指标加载到我在浏览器中运行的网页(Firefox)中。距离度量采用javascript函数的形式。
问题: 我试图通过文件输入将功能加载到我的网页中。但是,JS文档没有提供在脚本中导入函数的方法。我知道导入应该从脚本的顶部完成,但脚本不是事先加载的。
目前,我所拥有的是:
$("#param-distance").change(function () {
$('#div-param-dfunc').toggle($("#param-distance").val()==4);
});
$('#param-dfunc').change(function (){
var jsFileName = $('#param-dfunc')[0].files[0].name;
$.getScript(jsFileName).done( function (){
metric = dMetric; //metric has been defined in the global scope
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="param">
<label for="param-distance">Distance Metric</label>
<select id="param-distance" name="param-distance">
<option value="euclidean" selected="">Euclidean distance</option>
<option value="manhattan">Manhattan distance</option>
<option value="jaccard">Jaccard dissimilarity</option>
<option value="dice">Dice dissimilarity</option>
<option value=4>Other</option>
</select>
<output for="param-distance" id="param-distance-value"></output>
</div>
<div class="param" id="div-param-dfunc" style="display:none">
<label for="param-dfunc">Distance Metric File</label>
<input id="param-dfunc" type="file">
<output for="param-dfunc" id="param-dfunc-value"></output>
</div>
&#13;
以下是距离度量标准文件:
export default function dMetric(a,b){
/**
* Computes a distance between two points.
* The parameters should have the smae length
* Note that the distance metric should return a single non-negative value.
* It should also not return infinity.
* If the arrays are the same, dMetric should return 0.
* @param {Array} a
* @param {Array} b
* @return {Number} distance
*/
if(a.length!==b.length){
throw "The arrays have different lengths";
}
//Computation goes here. Store the distance as val.
var val = Math.abs(a-b);
return val;
}
&#13;
当我查看我的Firefox日志时,我看到2个语法错误:
SyntaxError: export declarations may only appear at top level of a module
ReferenceError: dMetric is not defined
我理解语法错误是因为我尝试在脚本中导入。 此外,参考错误可能是由于距离度量已加载但未运行。
我愿意接受建议。
最后,我认为PHP可能具有某种功能来解决这个问题,但我更倾向于坚持使用JavaScript和HTML。另外,如果可能的话,我宁愿不使用Node。