0

我尝试为一个项目创建一个简单的交通灯系统,但是一旦我使用 onclick="maakGroen();maakRood();"> 第二个功能就不起作用了....

这是我的代码

<input type="button" name="Licht" value="Licht" onclick="maakGroen();maakRood();">
<script>
  var Licht = document.getElementById('Licht');
  function maakRood() {
    Licht.src = "stop1.png";
  }
  function maakGroen() {
    Licht.src = "stop2.png";
  } 
4

4 回答 4

1

用于setTimeout()延迟第二个功能,以便您可以看到第一个功能的变化。

<input type="button" name="Licht" value="Licht" onclick="maakGroen();setTimeout(maakRood, 1000);">
于 2021-10-04T22:08:21.577 回答
0

尝试使用事件侦听器,在下面的示例中,您可以替换querySelectorgetElementByID; 有关开发人员网站的更多信息,或者您可以在 w3schools https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener上找到教程。

document.querySelector(".elementname").addEventListener("click", doStuff)

function doStuff() {
    maakGroen();
    maakRood(); 
}

如果您不喜欢这样,那么您可以简单地创建一个新函数,并将所有代码maakGroen();maakRood();粘贴到其中。

于 2021-10-04T22:14:09.053 回答
0

你在寻找类似的东西吗?
(你的问题真的不清楚!)

const trafficLights = document.querySelectorAll('.traffic-light')  

trafficLights.forEach(Tl => Tl.addEventListener('click', permuteTLcolor ))

function permuteTLcolor()
  {
  if (this.classList.contains('red'))    { this.classList.replace('red','green');    return }
  if (this.classList.contains('green'))  { this.classList.replace('green','yellow'); return }
  if (this.classList.contains('yellow')) { this.classList.replace('yellow','red');   return }

  this.classList.add('red')
  }
.traffic-light {
  display       : inline-block;
  width         : 2.6em;
  height        : 8em;
  border-radius : .7em;
  background    : #1c1641;
  margin        : 1em;
  padding-top   : .3em;
  cursor        : pointer;
  }
.traffic-light:hover {
  background    : #372c69;
  }
span {
  display       : block;
  width         : 2em;
  height        : 2em;
  border-radius : 50%;
  margin        : .4em .3em;
  box-sizing    : border-box;
  border        : .2em #97b2cc42 solid;
  }
.traffic-light > span:nth-of-type(1) { background: #441111; }
.traffic-light > span:nth-of-type(2) { background: #36360d; }
.traffic-light > span:nth-of-type(3) { background: #0b270b; }

.traffic-light.red    > span:nth-of-type(1) { background: #fc1515; border: 0; }
.traffic-light.yellow > span:nth-of-type(2) { background: #f3f314; border: 0; }
.traffic-light.green  > span:nth-of-type(3) { background: #28e728; border: 0; }
<div class="traffic-light red">
  <span></span><span></span><span></span>
</div>
<div class="traffic-light green">
  <span></span><span></span><span></span>
</div>
<div class="traffic-light yellow">
  <span></span><span></span><span></span>
</div>
<div class="traffic-light red">
  <span></span><span></span><span></span>
</div>

于 2021-10-04T22:41:49.827 回答
0

您可以创建包含两个函数的第三个函数,并像@Barmar 所说的那样使用超时。

于 2021-10-04T22:12:12.163 回答