简体   繁体   English

使用jQuery遍历表格-计算每一行的单元格

[英]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. 我有一个表,我想在其中计算jQuery的第六列。 I can identify the column by a class, CTR. 我可以按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: 我试图在jQuery中执行此操作,但是代码无法运行:

$( 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. 在td元素上调用val()不会返回内部html。 It return the value attribute. 它返回value属性。 If you are trying to get the html within the td element, call it like so: 如果您试图在td元素中获取html,请像这样调用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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