[英]Pass JS-arguments from HTML
This question is more about good practice. 这个问题更多的是关于良好实践的。 I want to write a JS-Module to plot math-functions onto canvas
-elements. 我想编写一个JS模块以将数学函数绘制到canvas
-elements上。 I know there are several good libraries out there, but I'm new to JavaScript and enjoy math. 我知道那里有几个不错的库,但是我是JavaScript新手,喜欢数学。
The user should use as little JavaScript as possible and I'm wondering how a good JS-library would behave. 用户应该使用尽可能少的JavaScript,我想知道一个好的JS库的表现如何。 Would the user have to write a specific id
for the canvas elements which should be used by the library? 用户是否需要为应该由库使用的canvas元素编写特定的id
? What should the user have to do to get a plot from x = -1 to x = 1 with grid turned on and green axes? 在网格打开且绿色轴打开的情况下,用户应该怎么做才能从x = -1到x = 1绘制图?
Would this be a good behavior? 这会是一个好行为吗?
<canvas id="plotJS, -1, 1, true, green">
I'm pretty sure this is awful, therefore I'm asking. 我很确定这很糟糕,所以我问。 Is there a convenient way to pass arguments to JS in the html
- code? 有没有一种方便的方法可以将参数传递给html
代码中的JS? Something like 就像是
<canvas id="whatever-i-want" plotJS-xMin="-1" plotJS-xMax="1" plotJS-grid="true" ... >
How is this normally done? 通常如何做?
An approach using JSON
, data-*
attributes as suggested by @SLaks . 一种使用JSON
和@SLaks建议的data-*
属性的方法。 At html
the data
attribute value is a single JSON
string, accessible at javascript
using HTMLElement.dataset
, JSON.parse()
; 在html
, data
属性值是单个JSON
字符串,可在javascript
使用HTMLElement.dataset
, JSON.parse()
; the dataset-plot-js
could also be reset at the element using JSON.stringify()
with parameter being data-plot-js
attribute string parsed as javascript
object 还可以使用JSON.stringify()
在参数处将dataset-plot-js
重置为参数,将data-plot-js
属性字符串解析为javascript
对象
var canvas = document.getElementById("canvas"); var data = JSON.parse(canvas.dataset.plotJs); console.log(data); // change `xMin` data.xMin = "-2"; canvas.dataset.plotJs = JSON.stringify(data); console.log(canvas.dataset.plotJs);
<canvas id="canvas" data-plot-js='{"xMin":"-1","xMax":"1","grid":"true","color":"green"}'></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.