简体   繁体   English

遍历JavaScript中的数组以在表单上产生按钮

[英]Iterate through an array in javascript to produce buttons on a form

Thanks for taking the time to read this question. 感谢您抽出宝贵的时间阅读此问题。

I have been working on a greasemonkey script (just loads an additional javascript on to a page to alter the content) to add buttons to a web form for a site I use a lot. 我一直在研究油脂猴子脚本(只需将其他JavaScript加载到页面上以更改内容)即可将按钮添加到我经常使用的网站的网络表单中。

var gt_all_the_stocks = [
    [   // Greetings
        ["Getting in touch", "Thank you for getting in touch,\n\n", "", "", "Added thank you", "",],
        ["Time on phone", "Thank you for your time on the phone today,\n\n", "", "", "Added thank you", "",],
        ["Getting back", "Thank you for getting back to us,\n\n", "", "", "Added thank you", "",],
    ],
    [   // Faults Stocks
        ["SFI Required", "An engineer is needed", "", "", "", "", ],    
    ]
];

The array is formatted with each row of buttons being a separate array and each button being an element on that row. 格式化该数组的格式是:每行按钮是一个单独的数组,每个按钮是该行上的一个元素。 So given the array above I should have two rows of buttons created, the first should contain 3 buttons and the second 1 button. 因此,鉴于上面的数组,我应该创建两行按钮,第一行应包含3个按钮,第二行应包含1个按钮。

I have written the following: 我写了以下内容:

//Create a button function
function addButton(container, text, onclickFunc) {
    // Create a new button
    var buttonnode= document.createElement('input');

    // Set some generic attributes
    buttonnode.setAttribute('type','button');
    buttonnode.setAttribute('name',text);
    buttonnode.setAttribute('value',text);
    buttonnode.setAttribute('class', 'gt_buttons');

    // Attach the event
    container.appendChild(buttonnode)
    buttonnode.addEventListener("click", onclickFunc, true);

    // Return it
    return buttonnode;
}

// Iterate through the array and make the buttons
for (var i1 = 0; i1 < gt_all_the_stocks.length; i1++) {

    console.log("Setting up row #" + i1 + " " + typeof i1);
    row = i1;

    for (var i2 = 0; i2 < gt_all_the_stocks[i1].length; i2++) {

        button = i2;

        addButton(make_div_above, gt_all_the_stocks[row][button][0], function(){
            if ( gt_all_the_stocks[row][button][1].length != 0 ){
                surround("", gt_all_the_stocks[row][button][1]);
            }
            if ( gt_all_the_stocks[row][button][2].length != 0 ){
                setSMS(gt_all_the_stocks[row][button][2]);
            }
            if ( gt_all_the_stocks[row][button][3].length != 0 ){
                setSignoff(gt_all_the_stocks[row][button][3]);
            }
            if ( gt_all_the_stocks[row][button][4].length != 0 ){
                console.log("Stock Tickets: " + gt_all_the_stocks[row][button][4]);
            }
            if ( gt_all_the_stocks[row][button][5].length != 0 ){
                setCause(gt_all_the_stocks[row][button][5]);
            }
        });
    }
    addHr(make_div_above);

}

The problem arises with the buttons that are created. 问题与创建的按钮有关。 The name on the buttons changes with each button, so the first button created in this instance has "Getting in touch" on it, while the second has "Time on phone" on it. 按钮上的名称随每个按钮而变化,因此在此实例中创建的第一个按钮上具有“保持联系”,而第二个按钮上具有“通话时间”。 However when the button is clicked the text that is generated is the text from the last button in the array. 但是,单击按钮时,生成的文本是数组中最后一个按钮的文本。

Basically if you click the button that says "Getting in touch" the text that comes out is "An engineer is needed", the text that relates to the button "SFI Required". 基本上,如果单击显示“取得联系”的按钮,则显示的文本为“需要工程师”,这是与按钮“需要SFI”相关的文本。

This might be a little bit of a rambling question but I am finding it difficult to say exactly what the problem is. 这可能是一个棘手的问题,但我发现很难确切地说出问题是什么。 My guess is that the variables row and button are being replaced on each iteration and the addButton function does not store the text and each iteration is replacing the text that is created. 我的猜测是变量行和按钮在每次迭代中都将被替换,并且addButton函数不存储文本,并且每次迭代都将替换创建的文本。

Potentially this would mean that generating a different variable name on each iteration, maybe something like title_button_row so for the title of the second button on row 3 would be title_1_2 but not sure how to do that. 潜在地,这意味着在每次迭代中生成不同的变量名,可能类似于title_button_row,因此对于第3行上第二个按钮的标题为title_1_2,但不确定如何执行。 PHP supports variable variable names like $title_$button_$row but I have no idea how to implement this is Javascript or even if this is a solution to this problem. PHP支持$ title_ $ button_ $ row之类的变量变量名,但我不知道如何使用Java语言来实现,即使这样也可以解决此问题。

I have put up a gist of the whole script here for reference https://gist.github.com/lgoldstien/5890269 我在这里提出了整个脚本的要点,以供参考https://gist.github.com/lgoldstien/5890269

Again, thanks for reading and I look forward to your responses. 再次感谢您的阅读,我们期待您的答复。

Calling functions which deals with DOM from loops results in issues like you are experiencing. loops调用处理DOM的函数会导致出现您遇到的问题。 To overcome this, peoples use various approaches like Array.forEach , Closures 为了克服这个问题,人们使用各种方法,如Array.forEachClosures

Wrap addButton call inside a self executing anonymous function & pass the variables to it. addButton调用包装在一个自执行的匿名函数中,并将变量传递给它。 Your problem will be solved. 您的问题将得到解决。 I am not sure you are a fan for Array.forEach . 我不确定您是否Array.forEach So I proposed Closure approach here. 因此,我在这里提出了Closure方法。

Like this:(Just the for loop part) 像这样:(只是for循环部分)

for (var i1 = 0; i1 < gt_all_the_stocks.length; i1++) {

console.log("Setting up row #" + i1 + " " + typeof i1);
row = i1;

for (var i2 = 0; i2 < gt_all_the_stocks[i1].length; i2++) {

    button = i2;

    (function(r, btn) {
      addButton(make_div_above, gt_all_the_stocks[r][btn][0], function(){
        if ( gt_all_the_stocks[r][btn][1].length != 0 ){
          surround("", gt_all_the_stocks[r][btn][1]);
        }
        if ( gt_all_the_stocks[r][btn][2].length != 0 ){
          setSMS(gt_all_the_stocks[r][btn][2]);
        }
        if ( gt_all_the_stocks[r][btn][3].length != 0 ){
          setSignoff(gt_all_the_stocks[r][btn][3]);
        }
        if ( gt_all_the_stocks[r][btn][4].length != 0 ){
          console.log("Stock Tickets: " + gt_all_the_stocks[r][btn][4]);
        }
        if ( gt_all_the_stocks[r][btn][5].length != 0 ){
          setCause(gt_all_the_stocks[r][btn][5]);
        }
      });
    })(row, button);
}
addHr(make_div_above);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM