我发现这个用纯 JavaScript 编写的非常短但方便的双向绑定代码。数据绑定工作正常,但我想要的是从第一个输入中获取值并将其乘以所需的数字并将结果绑定到下一个输入。我将不胜感激任何帮助。这是我的 HTML 代码:
<input class="age" type="number">
<input class="age" type="number">
和 JavaScript 代码:
var $scope = {};
(function () {
var bindClasses = ["age"];
var attachEvent = function (classNames) {
classNames.forEach(function (className) {
var elements = document.getElementsByClassName(className);
for (var index in elements) {
elements[index].onkeyup = function () {
for (var index in elements) {
elements[index].value = this.value;
}
}
}
Object.defineProperty($scope, className, {
set: function (newValue) {
for (var index in elements) {
elements[index].value = newValue;
}
}
});
});
};
attachEvent(bindClasses);
})();