.each()函数影响当前对象

.each() function on affect current object

本文关键字:对象 影响 函数 each      更新时间:2023-09-26

下面的代码有一些问题,首先这里是HTML:

<table class="finance-table">
  <tbody><tr>
    <th></th>
    <th>Deposit</th>
    <th>Balance</th>
    <th>Fees</th>
    <th>Total Payable</th>
    <th>Term</th>
    <th>Fixed Rate</th>
    <th>Representative APR</th>
    <th>Monthly Pmt</th>
  </tr>
  <tr class="hp">
    <td><strong>HP</strong></td>
    <td id="td_finance_deposit">£11700.00</td>
    <td id="td_finance_balance">£105300.00</td>
    <td id="td_finance_fees">£298.00</td>
    <td id="td_finance_total_inc_deposit">£146255.50</td>
    <td id="td_finance_term">60 mths</td>
    <td id="td_finance_rate">5.50%</td>
    <td id="td_finance_apr">10.1%</td>
    <td id="td_finance_monthly_payments">£2242.59 p/m*  x 60 mths</td>
  </tr>
</tbody></table>

在同一个文档中大约有10个这样的表,它们都具有相同的id和类。我使用each循环对找到的每个表执行一些代码,但是它似乎只在第一个表上工作,而忽略了其他表。

下面是jQuery,就像我说的在第一个表上找到的作品,但忽略其余的!

<!-- Remove First and Final Payment from Showroom Finance Examples -->
<script>
  $(".finance-table").each(function(key, value) {
    // Display loading
    var html = $(this);
    // Remove the First Payment and Final Payment Column
    $(this).find("#td_finance_first_payment, #td_finance_final_payment").remove();
    $(this).find("th:contains('1st Pmt')").remove(); $(this).find("th:contains('Final Pmt')").remove();
    // Get the Term and update the monthly payment
    var term = $(this).find("#td_finance_term").html(); // .replace(/'D/g,'')
    var payments = ($(this).find("#td_finance_monthly_payments").html()).split('x')[0];
    ($(this).find("#td_finance_monthly_payments")).html(payments + " x " + term);
  })
</script>

编辑:请注意,我根本无法更改HTML

您应该首先为每个<td>提供一个唯一的ID,也许是该记录的DB标识符。你现在不需要它,但这将允许你以后做其他事情,如果你需要它。

然后将所有<td> id更改为类:

<td class="td_finance_fees">£298.00</td>

最后改变你所有的javascript相应使用类而不是id:

$(this).find(".td_finance_first_payment, .td_finance_final_payment").remove();

使用属性=选择器

修改代码:

$(this).find("#td_finance_first_payment, #td_finance_final_payment").remove();

:

$(this).find('td[id="td_finance_first_payment"], td[id="td_finance_final_payment"]').remove();

#xxxid="xxx"的所有区域进行这种类型的更改

这样做的目的是找到所有属性id="xxx"的tds,而不是使用#id标识符,这是强制jQuery做树搜索。

你的HTML也不匹配你的代码,(没有td_finance_first_payment在你的HTML,我假设你删除了它?)

编辑:这个解决方案是有用的,如果你100%不能编辑html(来自一个源你没有控制,如API或内部软件)。最好的解决方案是修复id !