我正在開發一個使用重型輸入的遊戲過程。輸入事件監聽器從按鈕更新
Input1的值更改Input2的值。我已經開發了控件來增加或減少Input1的值。預期的結果是它會根據按鈕點擊或手動用戶更改來更改input2的值。
Input1和Input2都使用輸入和更改事件偵聽器。
在input1中手動輸入時,它會更改input2的值。但是,使用按鈕增大或減小input1值時,不會增加input2。
什麼是適當的事件監聽器在這種情況下使用。如果不是,我是否需要在按鈕點擊時調用計算功能。
大量的代碼切穿,但是這應該是所有的需要的東西
var game = {};
game.app = {
init: function() {
game.events.controls.init();
game.events.track.init();
},
}
game.calc = {
controls: {
increase: function(item) {
item = document.getElementById(item);
var size = item.getAttribute('data-size');
var max = item.getAttribute('data-max');
item.value = parseFloat(+item.value + 0.5).toFixed(size);
if (+max < item.value) {
item.value = (+max).toFixed(size);
}
}
},
track: {
act: function() {
document.getElementById('input2').value = (+document.getElementById('inputPlay').value + 100);
}
}
}
game.events = {
controls: {
init: function() {
this.increaseAction();
},
increaseAction: function() {
var increase = document.querySelectorAll('.increase');
for (var i = 0; i < increase.length; i++) {
increase[i].addEventListener('click', function(e) {
game.calc.controls.increase(e.target.getAttribute('data-src'));
return false;
});
}
}
},
track: {
init: function() {
this.actAction();
},
actAction: function() {
var inputPlay = document.getElementById('inputPlay');
inputPlay.addEventListener('input', function() {
game.calc.track.act();
});
inputPlay.addEventListener('change', function() {
game.calc.track.act();
});
}
}
}
game.app.init();
<a href="#" class="gameButton increase" data-src="inputPlay">Up</a>
<input type="text" id="inputPlay" name="inputPlay" value="100.00" class="inputMain" data-size="2" data-max="1000">
<input type="text" id="input2" name="input2" value="0.00" class="inputMain" data-size="2">
沒錯。這個解決方案的問題是,如果我需要擴展功能,我將無法做到。例如,如果我必須添加inputPlay2和input3來模擬效果,我將無法做到這一點。感謝您花時間幫忙 – Ray
有辦法讓我可以動態地傳遞函數名稱 – Ray
@ Ray對不起,我沒有意識到重用是您的目標,但是即使您要添加'inputPlay2'和'input3'其他許多東西也不起作用。你應該從一開始就設計它。 –