从HTML传递JS参数 [英] Pass JS-arguments from HTML
问题描述
这个问题更多的是关于良好实践的.我想编写一个JS模块以将数学函数绘制到canvas
元素上.我知道那里有几个不错的库,但是我是JavaScript新手,喜欢数学.
This question is more about good practice. I want to write a JS-Module to plot math-functions onto canvas
-elements. I know there are several good libraries out there, but I'm new to JavaScript and enjoy math.
用户应该使用尽可能少的JavaScript,我想知道一个好的JS库的表现如何.用户是否必须为应该由库使用的canvas元素编写特定的id
?用户应该怎么做才能在打开网格且绿轴的情况下从 x = -1 绘制到 x = 1 的图?
The user should use as little JavaScript as possible and I'm wondering how a good JS-library would behave. Would the user have to write a specific id
for the canvas elements which should be used by the library? What should the user have to do to get a plot from x = -1 to x = 1 with grid turned on and green axes?
这会是一个好行为吗?
Would this be a good behavior?
<canvas id="plotJS, -1, 1, true, green">
我很确定这很糟糕,因此我要问.是否有一种简便的方法可以在html
-代码中将参数传递给JS?像
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? Something like
<canvas id="whatever-i-want" plotJS-xMin="-1" plotJS-xMax="1" plotJS-grid="true" ... >
这通常如何完成?
推荐答案
@SLaks建议的使用JSON
和data-*
属性的方法.在html
处,data
属性值是单个JSON
字符串,可以在javascript
中使用
An approach using JSON
, data-*
attributes as suggested by @SLaks . At html
the data
attribute value is a single JSON
string, accessible at javascript
using 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
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>
这篇关于从HTML传递JS参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!