.each()函数影响当前对象
.each() function on affect current object
下面的代码有一些问题,首先这里是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();
对#xxx
到id="xxx"
的所有区域进行这种类型的更改
这样做的目的是找到所有属性id="xxx"的tds,而不是使用#id标识符,这是强制jQuery做树搜索。
你的HTML也不匹配你的代码,(没有td_finance_first_payment在你的HTML,我假设你删除了它?)
编辑:这个解决方案是有用的,如果你100%不能编辑html(来自一个源你没有控制,如API或内部软件)。最好的解决方案是修复id !
相关文章:
- 设置1400个Raphael.js对象的不透明度动画会影响动画性能
- 来自多个源的 jQuery 动画 - 影响多个对象
- 为什么引用 = null 不会影响引用的对象
- 是受(GWT)基类中方法数量影响的JavaScript对象的大小
- 函数和对象之间的差异,以及它如何影响性能
- 为什么更改函数的 .prototype 会影响已使用该构造函数创建的对象的“实例”
- 动态更改对象的大小,而不会影响其他元素
- 抽象脚本,以便单个页面上的每个选项卡对象实际上不会相互影响
- 将函数作为对象传递的Javascript会影响作用域
- ThreeJS-按不同顺序添加对象会影响alpha/显示
- JavaScript __proto__将影响对象中的原始函数
- 使用delete属性而不影响父对象
- 将对象与空引用进行比较时位置的影响
- pixi.js枢轴影响对象位置
- 缩小是如何工作的,它会影响有角度的嵌套对象吗
- 将函数原型设置为null对新创建的javascript对象没有影响
- return如何影响创建不带括号的对象的过程?
- .each()函数影响当前对象
- 影响现有实例的图表对象的新实例
- 在js对象中维护父引用是否有影响?