从textarea运行javascript n次

时间:2016-12-07 15:32:32

标签: javascript jquery

工作代码http://codepen.io/one2gov/pen/XNqyzB?editors=1111 此代码运行所有代码行,而不是只运行一行代码。怎么了?

oldVal = $("#fname").val();

lines = $("#fname").val().split(';');
lines.forEach(function(i, idx, array) {
    if (idx == lines.length - 1) {
        return;
    }
    element = $("<textarea></textarea>").attr({ 'id': '' + idx + '', 'class': "textar", 'style': "" }).html(idx+1);

    $("body").append(element)
});

$("#checkBtn").click(function() {

    $('textarea.textar').each(function(i, obj) {
        numbers = this.value;
        numbers = numbers*1;

        lines.forEach(function(i, idx) {
         test = lines[idx];
            if (idx == lines.length - 1) {
                return;
            }

            for (var i = 0; i < numbers; i++) {
                //console.log(numbers);
                eval(test);

            }

        })
    });
});

目标是多次运行代码行,作为行左侧textarea中的数字。 我期待在控制台中看到第一行代码触发一次,第二行触发2次。但相反,我会从所有行的两个数字中得到结果。

这是与demo的链接,它可以正常工作(但变量是假的)http://codepen.io/one2gov/pen/WoJyvB?editors=1011

1 个答案:

答案 0 :(得分:1)

checkBtn点击更改为:

$("#checkBtn").click(function() {
    $('textarea.textar').each(function(i, obj) {
        var numbers = this.value;
        numbers = numbers*1;

        // get only the current line
        var test = lines[i];

        // execute current line 'numbers' times
        for (var j = 0; j < numbers; j++) {
            eval(test);
        }

    });
});