首页 > 解决方案 > 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")

但是代码没有运行,所以我做错了什么,但看不到我做错了什么。

标签: javascript

解决方案


您缺少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)',
      },
    }
  });
}

推荐阅读