html 在javascript中创建/合并多个函数为一个(或至少更少)

z9gpfhce  于 2022-12-16  发布在  Java
关注(0)|答案(4)|浏览(171)

我有18个按钮可以点击,功能相同(点击它改变图像)为每个按钮,我想只使用1个功能,而不是18个。而且,每一个函数都有一个附加的函数,这个函数可以把数字和按钮的类打印到一个输入域中。2如果有人能帮我把所有这些代码精简成几个甚至一个函数,那就太棒了。只有纯html和javascript请。
这是我的javascript代码的前两个double函数:

function changeColor1() {
    if (document.getElementById("seatButton1").className == "seatLargeGreen") {
        document.getElementById("seatButton1").className = "seatLargeBlue";
    }
    else if (document.getElementById("seatButton1").className == "seatLargeBlue") {
        document.getElementById("seatButton1").className = "seatLargeGreen";
    }
}
seatButton1.addEventListener("click", function() {
    changeColor1();  
});
function num1() {
    if (document.getElementById('seatButton1').className === "seatLargeBlue") {
        document.getElementById('snum').value = 1;
        document.getElementById('sclass').value = "Business";
    }
    else {
        document.getElementById('snum').value = "";
        document.getElementById('sclass').value = ""
    }
}
seatButton1.addEventListener("click", function() {
    num1();
});
function changeColor2() {
    if (document.getElementById("seatButton2").className == "seatLargeGreen") {
        document.getElementById("seatButton2").className = "seatLargeBlue";
    }
    else if (document.getElementById("seatButton2").className == "seatLargeBlue") {
        document.getElementById("seatButton2").className = "seatLargeGreen";
    }
}
seatButton2.addEventListener("click", function() {
    changeColor2();  
});
function num2() {
    if (document.getElementById('seatButton2').className === "seatLargeBlue") {
        document.getElementById('snum').value = 2;
        document.getElementById('sclass').value = "Business";
    }
    else {
        document.getElementById('snum').value = "";
        document.getElementById('sclass').value = ""
    }
}
seatButton2.addEventListener("click", function() {
    num2();
});

还有16个类似的例子,下面是这部分的html:

<article class="column1">
   <table class="table_seats">
      <tr>
         <td id="seatButton1" class="seatLargeGreen" colspan="2">
            <button class="seat_button_large">
               1
            </button>
         </td>
         <td class="aisle" rowspan="3"></td>
         <td id="seatButton2" class="seatLargeGreen" colspan="2">
            <button class="seat_button_large">
               2
            </button>
         </td>
      </tr>
   </table>
</article>

我认为没有必要使用css。
我尝试使用document.querySelectorAll("#seatButton1, #seatButton2, ...")而不是document.getElementById(),但我无法使其工作。

zxlwwiss

zxlwwiss1#

一个更有效的方法是通过数据属性将相关数据(snum、sclass)附加到seat元素,并将元素传递给处理程序,然后事件处理程序将从单击的元素读取数据并进行适当更新,同时执行文档查询一次,并将结果存储在变量中。

const sclass = document.getElementById('sclass')
const snum = document.getElementById('snum')
const seats = document.querySelectorAll('td[class^="seat"]') // class attribute starts with...

function select(seat) {
  if (seat.className == "seatLargeGreen") {
    // find the previously selected seat
    let active = document.querySelector('.seatLargeBlue')
    if (active) { // if found deactivate
      active.className = 'seatLargeGreen'
    }

    seat.className = "seatLargeBlue";
    snum.value = seat.dataset.snum;
    sclass.value = seat.dataset.sclass;
  } else if (seat.className == "seatLargeBlue") {
    seat.className = "seatLargeGreen";
    snum.value = "";
    sclass.value = ""
  }
}

for (const [i, b] of seats.entries()) {
  b.addEventListener('click', e => select(e.currentTarget))
}
.seatLargeBlue button {
  background: blue;
  color: white;
}

.seatLargeGreen button {
  background: green;
  color: white;
}

.seat_button_large {
  padding: 1rem;
}
<article class="column1">
  <table class="table_seats">
    <tr>
      <td class="seatLargeGreen" colspan="2" data-snum="1" data-sclass="Business">
        <button class="seat_button_large">
          1
        </button>
      </td>
      <td class="aisle" rowspan="3"></td>
      <td class="seatLargeGreen" colspan="2" data-snum="2" data-sclass="Business">
        <button class="seat_button_large">
          2
        </button>
      </td>
      <td class="aisle" rowspan="3"></td>
      <td class="seatLargeGreen" colspan="2" data-snum="18" data-sclass="Economy">
        <button class="seat_button_large">
          18
        </button>
      </td>
    </tr>
  </table>
</article>
<input id="snum">
<input id="sclass">
guz6ccqo

guz6ccqo2#

捕获点击时携带所需信息的事件:

seatButton1.addEventListener("click", function(event) {
    console.log(event.target.textContent);
});
kognpnkq

kognpnkq3#

要弄清楚你想用代码做什么有点困难,因为它看起来不是一个完整的例子。例如,num 1和num 2引用的ID在示例HTML中不存在。这两个函数都对相同的2个ID起作用。
因此,很难知道下面的代码是否抓住了您想要做的事情的本质。它使事情更加模块化/基于组件,并在其中加入了一些“业务逻辑”联系,例如,看起来好像有一个状态围绕着某个东西是否是业务。
现在,我肯定会添加更多的更改来提高质量,并将业务价值从演示文稿中分离出来,但我没有太多的时间,而且我还担心,根据您发布的代码,这些更改可能太多了。

// This "Component" holds the logic for what a "Toggle button" is and defines it's behavior in an isolated way.
function ToggleButton(elm, onClick) {
  const button = elm.querySelector('.seat_button_large');
  let isBusiness = false;

  button.addEventListener('click', () => {
    isBusiness = !isBusiness;
    elm.className = isBusiness ? 'seatLargeBlue' : 'seatLargeGreen';
    onClick(isBusiness);
  });
}

// This "Component" holds the logic for what the "Display of last interaction" and we hook it up to the toggle buttons.
function LastToggleDisplay(elm) {
  const snum = elm.querySelector('#snum');
  const sclass = elm.querySelector('#sclass');
  this.set = (index, isBusiness) => {
    if (isBusiness) {
      snum.value = index;
      sclass.value = "Business";
    } else {
      snum.value = "";
      sclass.value = "";
    }
  }
}

const display = new LastToggleDisplay(document.getElementById("display"));
// The array here is just added so that our "ToggleButtons" are not just dangling, this can be important in cases where "Webapplications" grow in size and especially if we have a SPA as we then may need to clean things up as we change displays and all, so its more a habit than something I think you will really need here. Certain static analysis tools will complain if you just have dangling objects though.
const buttons = [];
for (let i = 1; i < 3; i++) {
  buttons.push(new ToggleButton(document.getElementById(`seatButton${i}`), isBusiness => display.set(i, isBusiness)));
}
.seatLargeGreen button {
  background-color: lightgreen;
  width: 42px;
  height: 42px;
}

.seatLargeBlue button {
  background-color: lightblue;
  width: 42px;
  height: 42px;
}
<div id="display">
  <input id="snum">
  <input id="sclass">
</div>
<article class="column1">
  <table class="table_seats">
    <tr>
      <td id="seatButton1" class="seatLargeGreen" colspan="2">
        <button class="seat_button_large">1</button>
      </td>
      <td class="aisle" rowspan="3"></td>
      <td id="seatButton2" class="seatLargeGreen" colspan="2">
        <button class="seat_button_large">2</button>
      </td>
    </tr>
  </table>
</article>
57hvy0tb

57hvy0tb4#

首先,你确实应该给它们都加一个类,表示它们是相关的,但是让我们给18个函数加一个,虽然这不一定是最好的解决方案,但是应该有相同的效果。
更新:通过使用Event.target属性在点击时引用正确的元素

for (var i = 1; i <= 18; i++) {

  var element_id = "seatButton" + i;
  var elem = document.getElementById(element_id);

  elem.addEventListener("click", function(ev) {
    var elem = ev.target;

    if (elem.className == "seatLargeGreen") {
      elem.className = "seatLargeBlue";
    } else if (elem.className == "seatLargeBlue") {
      elem.className = "seatLargeGreen";
    }

    if (elem.className === "seatLargeBlue") {
      document.getElementById('snum').value = 1;
      document.getElementById('sclass').value = "Business";
    } else {
      document.getElementById('snum').value = "";
      document.getElementById('sclass').value = ""
    }

  })

}

相关问题