【问题标题】:HTML pass constant or function to JavaScriptHTML 将常量或函数传递给 JavaScript
【发布时间】:2016-03-07 10:44:55
【问题描述】:

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

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

示例:

<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 方式更加灵活,但我将如何处理传入的数据实习生?

【问题讨论】:

  • 你能分享一个小提琴吗?
  • 小提琴应该包含什么?

标签: javascript html parameter-passing


【解决方案1】:

使用 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" />

【讨论】:

  • 这正是我想要的。非常感谢你:)
【解决方案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" />

【讨论】:

  • 我认为这里不应该使用 jQuery
  • 现在这不适用于 -1 作为属性。它会尝试调用一个常量。你可以看看你上面的答案。
猜你喜欢
  • 2016-08-21
  • 1970-01-01
  • 2012-01-07
  • 2015-05-02
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
相关资源
最近更新 更多