输入类型$ .each逐个更改值

时间:2014-08-23 07:11:49

标签: javascript jquery

我在dom中有一个低于另一个的输入类型,我可以和他们的名字一起选择。一旦他们根据其中存在的值进行渲染,我就必须更改他们的类。我正在做$ .each,但它也将最后一个类应用于所有其他元素。

$.each($("input[name='./items']"),function(i,val){
    var i =0;
    var date = JSON.parse(val.value);
    var startDate = new Date(date.startdate),
    endDate = new Date(date.enddate),
    today = new Date(new Date().toISOString());
    if((today-startDate>0) && (endDate-today>0)){
        $("input[name='./items']:eq(0)").parent().children('.x-panel').children('.x-panel-header').css('background-image','url(/libs/cq/ui/widgets/themes/default/ext/panel/green-top-bottom.gif)');
    }else if(today-startDate<0){
        $("input[name='./items']:eq(i)").parent().children('.x-panel').children('.x-panel-header').css('background-image','url(/libs/cq/ui/widgets/themes/default/ext/panel/blue-top-bottom.gif)');
    }else if(today-endDate>0){
        $("input[name='./items']:eq(i)").parent().children('.x-panel').children('.x-panel-header').css('background-image','url(/libs/cq/ui/widgets/themes/default/ext/panel/red-top-bottom.gif)');
    }
});

1 个答案:

答案 0 :(得分:1)

使用$(this)来引用迭代中的当前元素。此外,由于if/then/else块中有很多共同点,因此将其移出并为不同的块设置变量。

$("input[name='./items']").each(function(i,val){
    var date = JSON.parse(val.value);
    var startDate = new Date(date.startdate),
    endDate = new Date(date.enddate),
    today = new Date(new Date().toISOString());
    if((today-startDate>0) && (endDate-today>0)){
        var el = $("input[name='./items']:eq(0)");
        var color = 'green';
    }else if(today-startDate<0){
        el = $(this);
        color = 'blue';
    }else if(today-endDate>0){
        el = $(this);
        color = 'red';
    }
    if (el) {
        el.siblings('.x-panel').children('.x-panel-header').css('background-image', 'url(/libs/cq/ui/widgets/themes/default/ext/panel/' + color + '-top-bottom.gif)');
    }
});