当我单击按钮时,为什么我的按钮不执行该功能.它应该切换文字 [英] Why won't my button do the function when I click it it. It should toggle the text

查看:45
本文介绍了当我单击按钮时,为什么我的按钮不执行该功能.它应该切换文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

<button onclick="myFunction()">Try it</button>
<div id="myDIV">
  This is my DIV element.
</div>

我在W3Schools上找到了这段代码,并将"myDIV"替换为"h3",因此我可以更改标题中的文本

I found this code on W3Schools and replaced "myDIV" with "h3" so I can change the text in my header

    <div class="speech-buble-top"><h3 id="h3"> Happy Birthday Tiffany!</h3></div>

推荐答案

问题源于您使用 function 关键字声明了该函数.通常这很好,但是我发现使用HTML调用的javascript函数作为已分配给变量的函数更容易.如果使用ES6箭头语法,则将同时使用最新标准并将该函数绑定到变量.尝试像这样重写功能代码:

The issue stems from you declaring the function using the function keyword. Usually this is fine, but I find that it's easier to work with javascript functions called by HTML as functions that have been assigned to a variable. If you use ES6 arrow syntax, you'll both be using the latest standards and binding the function to a variable. Try rewriting the function code like so:

<script>
  myFunction = () => {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
    x.style.display = "block";
} else {
    x.style.display = "none";
   }
}
</script>
<button onclick="myFunction()">Try it</button>
<div id="myDIV" style="display: none">
  <h3 id="h3"> Happy Birthday Tiffany!</h3>
</div>

这篇关于当我单击按钮时,为什么我的按钮不执行该功能.它应该切换文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆