如何让我的 JavaScript 代码更干?

How can I make my JavaScript code more DRY?

我的代码看起来很乱,因为我不太习惯在 JavaScript 中编码。在 PHP 中,我会使用 for 循环和动态变量,但我无法让动态变量在 JavaScript 中工作。

你会怎样把它擦干?

document.getElementById("colorpicker01").onchange = function()  {myFunction01()};
function myFunction01() {  hexinput01.value = colorpicker01.value;}

document.getElementById("colorpicker02").onchange = function() {myFunction02()};
function myFunction02() {  hexinput02.value = colorpicker02.value;}

document.getElementById("colorpicker03").onchange = function() {myFunction03()};
function myFunction03() {  hexinput03.value = colorpicker03.value;}

document.getElementById("colorpicker04").onchange = function() {myFunction04()};
function myFunction04() {  hexinput04.value = colorpicker04.value;}

document.getElementById("colorpicker05").onchange = function() {myFunction05()};
function myFunction05() {  hexinput05.value = colorpicker05.value;}

document.getElementById("colorpicker06").onchange = function() {myFunction06()};
function myFunction06() {  hexinput06.value = colorpicker06.value;}

document.getElementById("colorpicker07").onchange = function() {myFunction07()};
function myFunction07() {  hexinput07.value = colorpicker07.value;}

document.getElementById("colorpicker08").onchange = function() {myFunction08()};
function myFunction08() {  hexinput08.value = colorpicker08.value;}

document.getElementById("colorpicker09").onchange = function() {myFunction09()};
function myFunction09() {  hexinput09.value = colorpicker09.value;}

document.getElementById("colorpicker10").onchange = function() {myFunction10()};
function myFunction10() {  hexinput10.value = colorpicker10.value;}

假设 myFunction 系列函数没有在其他地方使用,你会这样做:

var addChangeListener = function(elem, hexInput) {
    elem.onchange = function() {
        hexInput.value = elem.value;
    }
};

const elements = { 'colorpicker01':'hexinput01', 'colorpicker02':'hexinput02', 'colorpicker03':'hexinput03'}

for(elemName in elements) {
    const elem = document.getElementById(elemName);
    const hexInput = document.getElementById(elements[elemName]);
    addChangeListener(elem, hexInput);
}

如果您还需要重用 myFunction 函数,在运行时定义它们也很容易。