我有以下问题: 我有一个有 2 个输入元素的表。如果其中一个比另一个大,则整行应该根据比较来着色。我通过 onchange 事件触发此事件,并且是在加载网站时第一次触发。该过程工作正常,但 onchange 事件仅在 4 次更改中的 1 次中触发。
表语句如下:
<div class="grid">
<table id="table" class="tableRegion w100">
<thead style="text-align:left">
<tr>
<fmt:bundle basename="res/web/ec_resources">
<td class="tableHeader">
...
</td> ...
</fmt:bundle>
</tr>
</thead>
<tbody>
<c:set var="i" value="0"/>
<c:forEach var="participation" items="${someForm.list}">
<tr id="participationRow${i}">
这里是表 > tr > td 的代码:
<td class="right bottom nowrap">
<div>
<c:out value="${someForm.event.currency.code}"/>
<fmt:formatNumber maxFractionDigits="2" minFractionDigits="2" var="ovFee" value="${overallFee}" />
<c:if test="${someForm.array[i].feeDebit != 0.0}">
<spring:input class="right debit" path="array[${i}].feeDebit" maxlength="7" size="6" onchange="isPaid(${i});" />
</c:if><c:if test="${someForm.array[i].feeDebit == 0.0}">
<spring:input class="right debit" path="array[${i}].feeDebit" maxlength="7" size="6" onchange="isPaid(${i});" value="${ovFee}"/>
</c:if>
</div>
</td>
<td class="right bottom nowrap">
<div class="padT5"><c:out value="${someForm.event.currency.code}"/> <spring:input class="right paid" path="array[${i}].feePaid" maxlength="7" size="6" onchange="isPaid(${i});"/></div>
</td>
被调用的脚本如下:
$(document).ready(function(){
$('#table > tbody > tr').each(function(i) {
var paid = parseFloat($(this).find('input.paid').val());
var debit = parseFloat($(this).find('input.debit').val());
if (paid == debit)
$('#participationRow'+i).addClass("green");
else if (paid > debit)
$('#participationRow'+i).addClass("yellow");
}
);
});
function isPaid(i){
var paid = parseFloat($('#participationRow'+i).find('input.paid').val());
var debit = parseFloat($('#participationRow'+i).find('input.debit').val());
if (paid == debit)
$('#participationRow'+i).addClass("green");
else if (paid > debit)
$('#participationRow'+i).addClass("yellow");
}
偶尔触发一次事件的原因是什么?我用 jQuery 和 onclick 进行了交叉检查。它们都只是偶尔被触发一次。无论我是通过点击离开还是按 Tab 键离开。
最佳答案
当应该运行时,您的代码缺少触发器的任何定义。
第一部分(.each()
block )仅在 $(document).ready();
上执行,这意味着每页执行一次加载(文档加载完成后立即加载。)
isPaid()
函数只不过是一个函数,我看不到它在哪里被调用,因为它不存在于当前代码片段中。
您的代码本身似乎没问题,但它只是缺少任何形式的触发器。
你会期望类似的东西:
$("input").change(function() {
var the_row = $(this).parent().parent(); //finds the <tr> it belongs to.
var i = the_row.attr("id").replace("participationRow","");
isPaid(i);
});
有很多方法可以改进这一点,但这是您在代码中缺少的关键。
关于javascript - onChange 仅偶尔触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12955136/