考虑以下 fiddle :http://jsfiddle.net/danashurst/36mx3537/
HTML:
<table>
<tr>
<td>1 -</td>
<td>
<input id="1" class="primaryChannel" type="text" value="9">
</td>
</tr>
<tr>
<td>2 -</td>
<td>
<input class="channelValue" type="text" value="-4">
</td>
</tr>
<tr>
<td>3 -</td>
<td>
<input class="channelValue" type="text" value="5">
</td>
</tr>
</table>
Javascript:
filterInt = function (value) {
if (/^(\-|\+)?([0-9]+|Infinity)$/.test(value)) return Number(value);
return 0;
}
$('.channelValue').each(function () {
var elem = $(this);
// Save current value of element.
elem.data('oldVal', elem.val());
// Look for changes in the value.
elem.bind("propertychange change click keyup input paste", function (event) {
// If value has changed...
if (elem.data('oldVal') != elem.val()) {
// Calculate the difference between the old and the new value.
var difference = elem.data('oldVal') - elem.val();
// Updated stored value.
elem.data('oldVal', elem.val());
// Remove the difference from the first textbox.
$('.primaryChannel').attr("value", filterInt($('.primaryChannel').val()) + difference);
}
});
});
当用户更改文本框 2 或 3 的数值时,更改的差异会反射(reflect)在文本框 1 上。
但是,当用户更改文本框 1 的值,然后更改 2 或 3 的值时 - 然后似乎什么也没有发生 - 文本框 1 不会更改。
任何人都可以建议我实现这一目标的方法吗?
最佳答案
您正在使用.attr('value', someValue)
,但值属性设置默认值,而不是当前值。
改为设置值属性。使用 .val(someValue)
或 .prop('value', someValue)
。
关于javascript - 用户更改文本框的值后无法以编程方式更改文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28725102/