缩短重复(但长)的代码

Shortening repetitive (but long) code

我查看了有关缩短代码的不同帖子,但我发现很难将其应用到我的代码中。我仍处于初学者水平,我只是不知道如何开始。

我有一个函数需要重复 40 次。我已经从我的函数中上传了一个打印屏幕,它在 jQuery 中带有 jqPlot 插件。

它显​​示两个数据系列,用户可以单击图表以指示他认为时间系列中的下一个数据点。

每位用户将获得 40 张这样的图表。我目前拥有的代码是一个仅显示图 1 的函数。我必须对其进行循环,以便它显示所有 40 个图(40 个不同的时间序列),但每个用户的顺序不同(随机)。然而,我的第一个问题是在不使用重复代码的情况下使其重复。

编辑:根据 super-qua 的反应,我现在有以下代码:

我定义了以下全局变量(我暂时将自己限制在三个数据系列,缩短视图)

var index;
var promo1 = [0,81,102,..];
var s1 = [[0,301.961878917828],[1,287.301563144611],..,[50,285.689751451376]];
var promo2 = [0,184,0,..];
var s2 = [[0,286.723878917828],[1,444.439356046045]..,[50,323.874367563812]];
var promo3 = [0,196,0,..];
var s3 = [[0,250.478609608828],[1,416.973663811716],..,[50,335.79777763802]];

这是我的功能'Run'

var Run = function(){
    // create divs
 var graph = $('<div id="GRAPH' +index +'"><h4> Click on the graph to indicate the expected sales numbers for time period 51 and 52 (in that order). </h4></div>');
 var chart = $('<div id="chart' +index +'" style="width:800px;height:450px"></div>');
 var info = $('<div id="info' +index +'"></div>');
 var proceed = $('<div id="proceed'+index+'"><b>To change your forecast</b>, simply click on the graph. </p><p> <b>To save your forecast</b>, click the button below. </p><p> <button type="button" id="save1">Save forecast for time period 51</button> </p><p> <button type="button" id="submit">Submit my forecast</button> </p>');
 // append them to the graph div
 $(chart).appendTo(graph);
 $(info).appendTo(graph);
 $(proceed).appendTo(graph);
 var promo = $(promo+index);
 var s = $(s+index);
 $(plot).appendTo(chart);

 var plot = $.jqplot('chart'+index, [promo[index], s[index]], {
        stackSeries: false,
        series: [
        {label:'Promotions',
            renderer:$.jqplot.BarRenderer,
            rendererOptions: {
                barMargin: 12,
                barPadding: 0
                }
        },
        {label:'Sales', renderer:$.jqplot.LineRenderer, color:'grey', lineWidth: 2},
        ,
    {}
    ],   
            axesDefaults: {
                tickRenderer: $.jqplot.CanvasAxisTickRenderer,
                tickOptions: {
                angle: 0,
                fontSize: '8pt'

                }
                },
            axes: {
            xaxis: {
                tickInterval : 1,

                min: 0,
                max: 55
        },
            yaxis: {
                autoscale: true,
                min: 0
            }
        },
            cursor: {
                show: true,
                followMouse: true
            },
            legend: {
                renderer: $.jqplot.EnhancedLegendRenderer.min , 
                show: true,
                location: 'ne',
                placement: 'outside',
                marginRight: '50px'
            }
        });

 $(chart).bind('jqplotClick', function(event, seriesIndex, pointIndex, data) {
 xax51_s = pointIndex.xaxis; 
 yax51_s = pointIndex.yaxis;
s[index].push([pointIndex.xaxis,pointIndex.yaxis]);
console.log("Seriesnr" +index + xax51_s + " - " + yax51_s);
myDataRef.push("Seriesnr" +index + xax51_s + " - " + yax51_s);
if (Math.round(xax51_s1) === 51) {
    $('#info1').html("Your sales forecast for time period 51 is " + Math.round(yax51_s1) + " units.");
    $('#proceed1').show();
    $('#submit1').hide();
    //add new datapoint and renew dataserie s1
    plot1.series[1].data = [[0,301.961878917828],[1,287.301563144611],[2,333.856817030694],..[50,285.689751451376],[xax51_s1,yax51_s1]];
    //fill in replot/redraw!
    plot1.drawSeries({},1); 
}
//if they click outside of the 51st time period:
else {
   alert("Please click on the correct grid line (period 51)"); 
}
 });

  $(graph).appendTo('body');
};  

jquery 的其余部分保持简单并包括循环:

$('div').hide();
   $("#INTRO").show();
   $("#Start").click(function(){
       $("#INTRO").hide();
       for(var index=0; index<4; index++){
         Run(index);

我现在的问题是它似乎没有做任何事情。我得到一个空白页,表明 divs 不工作。我应该看到为 div "GRAPH" 创建的标题,但它没有显示。我还从 jqplot 得到消息说没有指定绘图目标,尽管它被指定为 'chart'。可能这也是因为没有创建 div。

实现这一目标的可能性有很多。 我会使用一个将索引作为参数的函数,为您创建 div,并将其附加到 dom。如果可以,您应该使用数组来存储数据,例如 promos.

它可能看起来像这样(未经测试 - 只是为了给你一个想法。所以我省略了一些东西):

var Run = function(index){
     // create your divs
     var graph = $('<div id="GRAPH' +index +'"><h4> Click on the graph to indicate the expected sales numbers for time period 51 and 52 (in that order). </h4></div>');
     var chart = $('<div id="chart' +index +'" style="width:800px;height:450px"></div>');
     var info = $('<div id="info' +index +'"></div>');

     // append them to the graph div
     $(chart).appendTo(graph);
     $(info).appendTo(graph);
     // add your proceed div the same way

     // finally append the graph div to your DOM
     $(graph).appendTo('body') // replace body with whatever your element container is

     var plot = $.jqplot('chart' +index, [promo[index], s[index]], {
     //(I have taken out all the settings here for the series so it doesn't get too messy) 

     $(chart).bind('jqplotClick', function(event, seriesIndex, pointIndex, data) {
     xax51_s = pointIndex.xaxis; // if you need to store the information for later use an array as well with xax51_s.push(pointIndex.xaxis)
     yax51_s = pointIndex.yaxis;

      // ... the rest of your code goes here

您可以在一个简单的循环中 运行 这 40 次。例如

for(var i=0; i<40; i++){
   Run(i);
}

注意:我不知道 jqplot,但它可能需要您在创建绘图之前附加图形。

希望这对您有所帮助。

更新:

如上更新,将 $(graph).appendTo('body') 移到 $.jqplot

之前

这就是你的数组应该看起来的样子

  var promo = [[0,81,102], [0,184,0], [0,196,0]];
  var s = [[[0,301.961878917828],[1,287.301563144611],[50,285.689751451376]], [[0,286.723878917828],[1,444.439356046045],[50,323.874367563812]], [[0,250.478609608828],[1,416.973663811716],[50,335.79777763802]]];

然后,我还注意到了两件事:

  • {label:'Sales', renderer:$.jqplot.LineRenderer, color:'grey', lineWidth: 2},
  • 行后面的逗号太多了
  • 去掉 var promo = $(promo+index); - 因为你已经有促销了

抓取并更新super-qua的答案

var promo = [], s = [];
for (i = 1; i < 41; i++) { //assuming that promo# and s# are both global variables.
    promo[i] = window["promo"+i];
    s[i] = window["s"+i];
}
var Run = function(index){
 // create your divs
 var graph = $('<div id="GRAPH' +index +'"><h4> Click on the graph to indicate the expected sales numbers for time period 51 and 52 (in that order). </h4></div>');
 var chart = $('<div id="chart' +index +'" style="width:800px;height:450px"></div>');
 var info = $('<div id="info' +index +'"></div>');

 // append them to the graph div
 $(chart).appendTo(graph);
 $(info).appendTo(graph);
 // add your proceed div the same way

 var plot = $.jqplot('chart' +index, [promo[index], s[index]], {
 //(I have taken out all the settings here for the series so it doesn't get too messy) 

 $(chart).bind('jqplotClick', function(event, seriesIndex, pointIndex, data) {
 xax51_s = pointIndex.xaxis; // if you need to store the information for later use an array as well with xax51_s.push(pointIndex.xaxis)
 yax51_s = pointIndex.yaxis;

  // ... the rest of your code goes here

  // finally append the graph div to your DOM
  $(graph).appendTo('body') // replace body with whatever your element container is
}

我只能说,如果 .jqplot 需要 div 已经呈现在页面上,这将不起作用,除非您使用相同的循环呈现所有 divs/charts/info,否则隐藏它们。