开发者

jQuery sum values from items above

I have small problem.

What I want to achieve is adding sum of values from above elements to each one. For example every position have got it own time value hidden in attribute. I can get it by using jQuery

var time = $(ui.draggable).attr("time");

now we got 4 positions with time as follows:

  1. 432 sec
  2. 123 sec
  3. 5634 sec
  4. 654 sec

Now I want to sum it like this:

1. 432
2. 432+12开发者_运维技巧3
3. 432+123+5634
4. 432+123+5634+654

Any ideas how can I do this?

This is my code:

$(document).ready(function(){

    $(".trash").sortable({
        tolerance: 'touch',
        receive: function (event, ui) {
        ui.item.remove();
           }
    });
    $(".DragContainer_dest").sortable({helper:'clone',
        opacity: 0.5,
        connectWith: '.trash',
        scroll: true,
        update : function () { 
        var order = $('.DragContainer_dest').sortable('serialize',{key:'string'}); 
        $.post('includes/ajaxify.php',order+'&action=update');    
        var time = $(this).attr("time");
        },
        out : function () { 
            ui.item.remove();
        }
    });

    $("div[class=DragContainer] .DragBox").draggable({helper:'clone'}); 

    $(".DragContainer_dest").droppable({
        accept: ".DragBox",
        tolerance: "touch",
        drop: function(ev, ui) {
           $(this).append($(ui.draggable).clone().addClass("added"));  
        }
    });
  });

I want every element dropped or sorted in DragContainer_dest to sum values from other elements above him. Can this be done?


As I can understand, you need to collect all siblings of a node that come before the element in question and collect their attributes. Let's try this:

var nodeSiblings = $(this).parent().children();
// We need to find the index of our element in the array
var stopIndex = nodeSiblings.index(this);
var time = 0;

nodeSiblings.each( function(index, element){
    if (index > stopIndex) return;
    var attribute = parseInt($(element).attr("time"), 10);
    if (!isNaN(attribute)) time += attribute;
});

// Here you have the sum of all time attributes
alert(time);


Maybe add a global variable called timeSum and then increase it for each element dropped?

var timeSum = 0;

$(".DragContainer_dest").droppable({
    drop: function(ev, ui) {
       timeSum += parseInt($(ul.draggable).attr('time'));
    }
});


If you're using parseInt as instructed elsewhere, don't forget to include the radix:

parseInt($(ul.draggable).attr('time'), 10);

If you have a zero at the start it will treat it as octal unless you specify the radix.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜