简体   繁体   中英

Looping through table with jQuery - calculating cell in for each row

I have a table where I want to calculate the sixth column in jQuery. I can identify the column by a class, CTR.

    <table class="table">
         <tr>
            <td class="date">08-05-2014</td>
            <td class="spend">615,68</td>
            <td class="impressions">71996</td>
            <td class="clicks">30</td>
            <td class="leads">3</td>
            <td class="CTR">—</td>
            <td class="eCPM">—</td>
            <td class="eCPC">—</td>
            <td class="eCPL">—</td>
         </tr>
         <tr>
            <td class="date">09-05-2014</td>
            <td class="spend">1983,44</td>
            <td class="impressions">398429</td>
            <td class="clicks">115</td>
            <td class="leads">15</td>
            <td class="CTR">—</td>
            <td class="eCPM">—</td>
            <td class="eCPC">—</td>
            <td class="eCPL">—</td>
         </tr>
    </table>

I want the CTR to be calucated as the number of clicks divided by the number of impressions for that given row. I have attempted doing this in jQuery but the code does not run:

$( document ).ready(function() {
  $('table tr').each(function(index) {
  $this = $(this)
  var imps = $this.find("td.impressions").val();
  var clicks = $this.find("td.clicks").val();
  var ctr = $this.find("td.CTR").val();
  ctr = parseFloat(clicks) / parseFloat(imps) * 100;
  });
});

What am I doing wrong? - How should the code look like?

[UPDATE] I have adopted the code due to the replies. This still does not run:

$( document ).ready(function() {
  $('tr').each(function(index) {
    $this = $(this)
    var imps = $this.find(".impressions").html();
    var clicks = $this.find(".clicks").html();
    $this.find(".CTR").html() = parseFloat(clicks) / parseFloat(imps);
  });
});

The console tells me "Invalid left-hand side in assignment" for the assignment in the last line.

[SOLVED]

$( document ).ready(function() {
  $('tr').each(function(index) {
    $this = $(this)
    var imps = $this.find(".impressions").text();
    var clicks = $this.find(".clicks").text();
    $this.find(".CTR").text(parseFloat(clicks) / parseFloat(imps) * 100);
  });
});

Calling val() on the td element does not return the inner html. It return the value attribute. If you are trying to get the html within the td element, call it like so:

$this.find("td.impressions").html();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM