JQuery: how to get the sum of the width of all previous elements and put it in a data attribute

how to get the width of each previous element and sum them up (after loading the page)

Then put the value in the data attribute of each item

This is the jsfiddle code http://jsfiddle.net/jSfKJ/2/

so how to make this code

<ul> <li style="width:130px">Num 1</li> <li style="width:150px">Num 2</li> <li style="width:140px">Num 3</li> <li style="width:175px">Num 4</li> <li style="width:100px">Num 5</li> </ul> 

to be like that -

 <ul> <li style="width:130px" data-num="0">Num 1</li> <li style="width:150px" data-num="130">Num 2</li> <li style="width:140px" data-num="280">Num 3</li> <li style="width:175px" data-num="420">Num 4</li> <li style="width:100px" data-num="595">Num 5</li> </ul> 

This image to more clearly explain what I want | enter image description here
I hope I explained what I need.

+4
source share
3 answers

Easy way to do this: http://jsfiddle.net/jSfKJ/5/

you save var, add element width in each:

 (function(){ var total = 0; $('li').each(function() { $(this).attr('data-num', total) total += $(this).width() }); })(); 

This method reduces each to 1

+6
source
 var globalheight = 0; $(document).ready(function(){ $('ul li').each(function(){ $(this).attr({'data-num':globalheight}); globalheight = globalheight+$(this).width(); }); }); 
0
source

Just repeat as you have in your violin something like the following:

 var ctr = 0; $('li').each(function() { var itm = $(this); itm.data().num = ctr; ctr += itm.width(); }); // below just to show u the output. $('li').each(function (){ console.log($(this).data()); }); 

It is unclear whether you want to save the data or want it to be the actual attribute visible in the markup. If you see, just add them as itm.attr ('num', ctr);

0
source

Source: https://habr.com/ru/post/1481554/


All Articles