HTML 将常量或函数传递给 JavaScript

HTML pass constant or function to JavaScript

本文关键字:JavaScript 函数 常量 HTML      更新时间:2023-09-26

我目前正在编写一个JavaScript库来绘制浏览器中的函数。用户包括库,并向页面添加特定类的div。他能够通过div的属性告诉图书馆要绘制data-*什么。

现在我确实希望用户能够将常量值或 javascript-functions 作为参数传递,并且我的库读取常量或计算函数。我该怎么做?

例:

<script>
function range-value() {
  var range = document.getElementById("random-range");
  return range.value;
}
</script>
<div class="plot-example" data-plot-xMin="-1"></div>
<div class="plot-example" data-plot-xMin="range-value"></div>

这将使 lib 的方式更加灵活,但是我将如何处理传入的数据实习生?

使用 eval 和 type of 来判断函数和 num 之间的差异并调用函数。如果"rangeValue"(eval =>函数)写成"rangeValue()"(eval => number),则可以使用 eval。

function rangeValue() {
  var range = document.getElementById("random-range");
  return range.value;
}
function rangeValue2(num) {
  return num + 10;
}
var divs = document.getElementsByClassName("plot-example");
for (var i = 0; i < divs.length; i++) {
  var val = eval(divs[i].getAttribute("data-plot-xMin"));
  var trueval = null;
  if (typeof val === 'function') {
    trueval = val();
  } else {
    trueval = val;
  }
  document.write("<br>" + trueval);
}
<div class="plot-example" data-plot-xMin="-1"></div>
<div class="plot-example" data-plot-xMin="rangeValue"></div>
<div class="plot-example" data-plot-xMin="rangeValue2(3)"></div>
<input id="random-range" value="2" />

您可以通过

获取属性的值并通过window['the_function_name']访问函数来做到这一点。

喜欢这个:

[].forEach.call(document.querySelectorAll('.plot-example'), function(elm) {
  var f = window[elm.getAttribute('data-plot-xMin')];
  if (f) {
    elm.innerHTML = window[elm.getAttribute('data-plot-xMin')].call();
  }
});
<script>
function rangeValue() {
  var range = document.getElementById("random-range");
  return range.value;
}
</script>
<div class="plot-example" data-plot-xMin="-1"></div>
<div class="plot-example" data-plot-xMin="rangeValue"></div>
<input type="range" id="random-range" />