jQuery每个增量问题

时间:2013-10-31 11:59:48

标签: javascript jquery variables loops each

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

在进一步测试中,我发现有几次attr方法无法设置属性。我更改了以下代码行以简化:

$(this).attr('name', 'yahoo');

afterRemoveCurrent事件被触发后

console.log上面的代码行应该执行的$(this),令我惊讶的是该属性没有更改为{{1 }}。我重复了几次,发现有几次属性被改变,有时则没有改变。我使用yahoosetTimeout内的整个函数的执行延迟了500毫秒,但结果仍然相同。这有帮助吗?

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

我有一小段代码没有按预期工作。我正在使用一个名为sheepit http://www.mdelrosso.com/sheepit/index.php?lng=en_GB的插件(允许您添加多个表单字段):

此处可以看到该页面的实时版本:

此语句afterRemoveCurrent中的i有时会被错误地评估。更具体一点:

变量$(this).attr('name', 'rooms[' + i + ']' + '.' + arr[1] + '.' + arr[2]);在以下2个参数(每个循环)中应相同:

i
$(this).attr('data-index', i);

但是,当第一个语句中$(this).attr('name', 'rooms[' + i + ']' + '.' + arr[1] + '.' + arr[2]);的值为i时,不知何故,有几次,0或第二个语句中的其他数字。

1

2 个答案:

答案 0 :(得分:1)

使用闭包:

afterRemoveCurrent: function(source) {
    (function(i) {
        $('select.children').each(function() {
            $(this).attr('data-index', i);
            $(this).parent().find('select.child-age-option').each(function() {
                var arr = $(this).attr('name').split('.');
                $(this).attr('name', 'rooms[' + i + ']' + '.' + arr[1] + '.' + arr[2]);
            });
            i++;
        });
    })(0);
}

答案 1 :(得分:0)

试试这个

var sheepItForm = $('#sheepItForm').sheepIt({
    separator: '',
    allowRemoveLast: false,
    allowRemoveCurrent: true,
    allowAdd: true,
    maxFormsCount: 8,
    minFormsCount: 1,
    iniFormsCount: 0,
    pregeneratedForms: ['pregenerated_form_1'],
    afterRemoveCurrent: function(source) {
        $('select.children').each(function(i) {
            $(this).attr('data-index', i);
            $(this).parent().find('select.child-age-option').each(function() {
                var arr = $(this).attr('name').split('.');
                $(this).attr('name', 'rooms[' + i + ']' + '.' + arr[1] + '.' + arr[2]);
            });
        });
    }
});