javascript - Working with jQuery index in a each function -
javascript - Working with jQuery index in a each function -
i have 2 questions,
first, want calculate percentage in html page , homecoming javascript appending it. works fine sets everywhere same value. think need 'this' can't find how work. each function doesn't remain within li, sets everywhere.
another problem var getalfavconvert = parsefloat(getalfav.substring(1));
reason returns unusual value. var getalconvert = parsefloat(getal.substring(1));
on other hand works fine. think has link.
another problem
$(".thing-shot ul").prepend('<li class="hammer">10%</li>'); $('.things li .group').each(function(index) { // value page var getal = $('.current-user-view').text(); var getalfav = $('.fav.marked a').text(); // convert value float var getalconvert = parsefloat(getal.substring(1)); var getalfavconvert = parsefloat(getalfav.substring(1)); //make percentage calculation var gedeeld = getalconvert/getalfavconvert; var percentage = gedeeld*100; // set percentage in html $(".hammer").text(percentage); });
here construction of li in html:
<li id="screenshot-2081" class="group"> <div class="athing"> <div class="thing-shot"> <div class="thing-img"> <a href="go.html" class="link"><img alt="teaser" src="teaser.png?1310142565" /></a> </div> <ul class="tools group"> <li class="fav marked"> <a href="go.html">21</a> </li> <li class="cmnt current-user-cmnt "> <a href="#">6</a> </li> <li class="views current-user-view"> 276 </li> </ul> </div> <div class="extras"> </div> </div> </li>
the 'changing everywhere' problem have quite mutual one, you're selecting all objects of class. want find children of each object when using .each()
using $(this)
, using .children()
selector.
i've edited jquery reflect these changes:
$(".shot ul").prepend('<li class="hammer">0%</li>'); $('.things li .group').each(function(index) { // value page var getal = $(this).children('.current-user-view').text(); var getalfav = $(this).children('.fav.marked').find("a").text(); // convert value float var getalconvert = parsefloat(getal.substring(1)); var getalfavconvert = parsefloat(getalfav.substring(1)); //make percentage calculation var gedeeld = getalconvert/getalfavconvert; var percentage = gedeeld*100; // set percentage in html $(this).children(".hammer").text(percentage); });
edit
if @ code above, you'll see
var getalfav = $(this).children('.fav.marked').find("a").text();
the key here .find("a")
- actual <a>
tag isn't kid of <ul>
, sub-child .children()
doesn't like, hence .find()
. way this:
var getalfav = $(this).children('.fav.marked').text();
this still gives right value because .text()
strips html contents , leaves number. i'd recommend .find()
method though it's easier read , semantically correct, fact other added content mess things up.
take at jsfiddle illustration :-)
javascript each
Comments
Post a Comment