如何保留onclick函数的结果

时间:2019-05-23 16:11:44

标签: javascript onclick innerhtml

我正在为网格旋转器编写JavaScript函数,该函数应在单击一个按钮时旋转按钮。

我正在开发一种网格旋转器,该网格旋转器由3x3网格形式组成,带有标记为1-9的按钮。当单击5时,我的代码应旋转外部按钮。当我单击按钮时,它们旋转,但立即返回其初始状态。请帮助我确保轮换结果保持不变。这是我第二天编码JS。

Button_5.onclick = function() {
  var viarableNum = Button_1.innerHTML;
  Button_1.innerHTML = Button_4.innerHTML;
  Button_4.innerHTML = Button_7.innerHTML;
  Button_7.innerHTML = Button_8.innerHTML;
  Button_8.innerHTML = Button_9.innerHTML;
  Button_9.innerHTML = Button_6.innerHTML;
  Button_6.innerHTML = Button_3.innerHTML;
  Button_3.innerHTML = Button_2.innerHTML;
  Button_2.innerHTML = viarableNum;
}
form {
  display: grid;
  grid-column-gap: 4px;
  grid-template-columns: auto auto auto;
  background-color: rgb(182, 95, 95);
  padding: 4px;
  width: 400px;
  height: 400px;
  margin-left: 40%;
  margin-top: 10%;
}

.button {
  background-color: rgba(212, 210, 68, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 4px;
  font-size: 40px;
  text-align: center;
  font-weight: bold;
  cursor: pointer;
}
<!DOCTYPE HTML>
<head>
  <title>Rotate</title>
</head>
<body>
  <form>
    <button id="Button_1" class="button">1</button>
    <button id="Button_2" class="button">2</button>
    <button id="Button_3" class="button">3</button>
    <button id="Button_4" class="button">4</button>
    <button id="Button_5" class="button">5</button>
    <button id="Button_6" class="button">6</button>
    <button id="Button_7" class="button">7</button>
    <button id="Button_8" class="button">8</button>
    <button id="Button_9" class="button">9</button>
  </form>
</body>
</html>

当单击5时,我的预期输出应保持onclick函数的结果。它适用于div标签,但不适用于表单。请帮忙。预先感谢

2 个答案:

答案 0 :(得分:0)

默认情况下,单击表单内的按钮会提交表单,并重新加载当前页面。为按钮指定“按钮”类型,以免触发表单提交。

<form>
<button type="button" id="Button_1" class="button">1</button>
<button type="button" id="Button_2" class="button">2</button>
<button type="button" id="Button_3" class="button">3</button>
<button type="button" id="Button_4" class="button">4</button>
<button type="button" id="Button_5" class="button">5</button>
<button type="button" id="Button_6" class="button">6</button>
<button type="button" id="Button_7" class="button">7</button>
<button type="button" id="Button_8" class="button">8</button>
<button type="button" id="Button_9" class="button">9</button>
</form>

或删除<form>标签。

答案 1 :(得分:-1)

export class HeroResult { heroes: Hero[]; } getHeroes(): Observable<Hero[]> { return this.http.get<HeroResult>(this.heroesUrl).pipe( map(res => res.heroes) ); } 放置为功能的最后一部分-这将阻止“自然”按钮/提交动作的完成。