更新DOM中同一级别的下一个元素

时间:2011-04-26 14:00:55

标签: jquery

我有这段代码:

<div class="trackOn" id="line1">
    <span class="trackCounter">1</span>
    <span class="trackTime1">
        <select name="hours[]" class="trackInputDate" onChange="updateHours(this.value)" >
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>                
        </select>
    </span>
    <span class="trackTime2"></span>
    <span class="trackTime3"></span>
</div>

<div class="trackOn" id="line2">
    <span class="trackCounter">2</span>
    <span class="trackTime1">
        <select name="hours[]" class="trackInputDate" onChange="updateHours(this.value)" >
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>                
        </select>
    </span>
    <span class="trackTime2"></span>
    <span class="trackTime3"></span>
</div>

<div class="trackOn" id="line3">
    <span class="trackCounter">3</span>
    <span class="trackTime1">
        <select name="hours[]" class="trackInputDate" onChange="updateHours(this.value)" >
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>                
        </select>
    </span>
    <span class="trackTime2"></span>
    <span class="trackTime3"></span>
</div>

<div class="trackOn" id="line4">
    <span class="trackCounter">4</span>
    <span class="trackTime1">
        <select name="hours[]" class="trackInputDate" onChange="updateHours(this.value)" >
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>                
        </select>
    </span>
    <span class="trackTime2"></span>
    <span class="trackTime3"></span>
</div>

现在,例如,如果我从3中选择值#line2,我想更改下一个选择框的值(所以#line3和{{{ 1}})#line4

1 个答案:

答案 0 :(得分:1)

最好使用jQuery附加事件处理程序:

$('.trackInputDate').change(function() {
    updateHours($(this).val()); // or was `updateHours` supposed to be the 
                                // function that should handler the update?
    $(this).closest('.trackOn')
        .nextAll('.trackOn')
        .find('.trackInputDate').val($(this).val());
});

参考:.closest.nextAll.find


必须先完整解析DOM,然后才能附加事件处理程序。所以要么将代码放在ready()事件处理程序中:

$(function() {
   // code here
});

或将其放在页面底部。