javascript - JavaScript 函数
问题描述
我想将以下内容粘贴到一个函数中,因为我目前正在多次调用它。
var chart = LightweightCharts.createChart(document.getElementById("chart"), {
width: 250,
height: 250,
layout: {
textColor: '#d1d4dc',
backgroundColor: 'black',
},
localization: {
priceFormatter: formatters[formatterNames[0]],
},
priceScale: {
borderColor: 'rgba(255, 255, 255, 0.8)',
},
timeScale: {
visible: false,
borderColor: 'rgba(255, 255, 255, 0.8)',
},
priceScale: {
scaleMargins: {
top: 0.3,
bottom: 0.25,
},
},
grid: {
vertLines: {
color: 'rgba(255, 255, 255, 0.2)',
},
horzLines: {
color: 'rgba(255, 255, 255, 0.2)',
},
},
});
我想我会把它添加到这样的函数中:
function Makechart (chartname){
LightweightCharts.createChart(document.getElementById(chartname), {
width: 250,
height: 250,
layout: {
textColor: '#d1d4dc',
backgroundColor: 'black',
},
localization: {
priceFormatter: formatters[formatterNames[0]],
},
priceScale: {
borderColor: 'rgba(255, 255, 255, 0.8)',
},
timeScale: {
visible: false,
borderColor: 'rgba(255, 255, 255, 0.8)',
},
priceScale: {
scaleMargins: {
top: 0.3,
bottom: 0.25,
},
},
grid: {
vertLines: {
color: 'rgba(255, 255, 255, 0.2)',
},
horzLines: {
color: 'rgba(255, 255, 255, 0.2)',
},
},
});
然后通过将变量设置为函数来调用它
Var chart1 =Makechart("chart1")
Ver chart2 =Makechart("chart1")
但是代码没有运行,所以我做错了什么,但看不到我做错了什么。
解决方案
您缺少return
从函数返回值的关键字。
如果图表之后无法初始化,那么您可能应该检查控制台是否有错误。
在第一个示例中,您选择一个 id 为 的元素,chart
在后面的示例chart1
中。确保您的元素存在。
function Makechart(chartname) {
return LightweightCharts.createChart(document.getElementById(chartname), {
width: 250,
height: 250,
layout: {
textColor: '#d1d4dc',
backgroundColor: 'black',
},
localization: {
priceFormatter: formatters[formatterNames[0]],
},
priceScale: {
borderColor: 'rgba(255, 255, 255, 0.8)',
},
timeScale: {
visible: false,
borderColor: 'rgba(255, 255, 255, 0.8)',
},
priceScale: {
scaleMargins: {
top: 0.3,
bottom: 0.25,
},
},
grid: {
vertLines: {
color: 'rgba(255, 255, 255, 0.2)',
},
horzLines: {
color: 'rgba(255, 255, 255, 0.2)',
},
}
});
}
推荐阅读
- git - 如何在多个工作站之间共享 Git 别名?
- azure - 在 Azure 中监控服务
- c++ - 读取包含数据类型为 arrow::large_utf8() 的列的羽毛文件时出现分段错误
- css - 是否可以在 CSS 中组合或嵌套多个“@-rules”......在执行规则之前需要不同的“@”?
- jquery - 如果jQuery中的警报消息不相等,如何匹配两个输入值?
- xcode - 如何在构建日志中捕获 Xcode 构建后操作输出?
- c++ - 为什么即使在我输入错误后我的功能仍在继续?
- javascript - A-frame 将我的 div 中的代码镜像到 2d 平面上
- android - 如何调整 AutoCompleteTextView 的样式以匹配 TextInputEditText 的样式
- python - 使用 Beautiful Soup 和 python 抓取登录和 2 因素身份验证