缩短重复(但很长)的代码

时间:2015-01-22 09:59:02

标签: jquery html repeat

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

我有一个需要重复40次的功能。我已经从我的函数上传了一个打印屏幕,这是在jQuery中使用jqPlot插件。

它显示两个数据系列,用户可以点击图表来表明他认为将成为时间序列中的下一个数据点。

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

编辑:基于超级反应,我现在有以下代码:

我定义了以下全局变量(我目前仅限于三个数据系列,缩短了视图)

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]];

这是我的功能'运行'

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);

我现在面临的问题是它似乎没有做任何事情。我得到一个空白页面,表明div不起作用。我应该看到为div&#34; GRAPH&#34;创建的标题,但它没有显示。我还从jqplot获得了没有指定绘图目标的消息,尽管这被指定为&#39; chart&#39;。可能这也是因为没有创建div。

2 个答案:

答案 0 :(得分:0)

实现这一目标有很多可能性。 我将使用一个以索引作为参数的函数,为您创建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); - 因为你已经宣传

答案 1 :(得分:0)

抓住并更新超级答案。

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已经在页面上呈现,这将无效,除非你使用相同的循环渲染所有的div / charts / info,否则隐藏它们。