从HTML传递JS参数 [英] Pass JS-arguments from HTML

查看:468
本文介绍了从HTML传递JS参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题更多的是关于良好实践的.我想编写一个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建议的使用JSONdata-*属性的方法.在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆