【问题标题】:Onclick event with if condition in javascript htmljavascript html中带有if条件的Onclick事件
【发布时间】:2021-11-08 06:50:35
【问题描述】:

对编码很陌生。但是我有一个小任务,我只是不知道我应该做什么或应该如何写下来。基本上它应该给出一个输入框和一个按钮(这可行)。但是现在我想在输入为 hi 时发出警报,如果输入为 bye 则发出不同的警报。对于所有其他输入,不应该发生任何事情。我就是不明白,有人能帮忙吗?

<h1>Welcome</h1>

    Input: <input id="welcome1" type="text" />

    <button id="button">Click here</button>
    
   </body>
   <script type="text/javascript">

    if (document.getElementById("welcome1").textContent = "hi"){
        document.getElementById("button").onclick = alert("Welcome");
    }
    else (document.getElementById("welcome1").textContent = "bye"){
        document.getElementById("button").onclick = alert("See you later");  
    }

   </script>

【问题讨论】:

  • onclick 需要一个函数。 alert("Welcome") 不是函数。在if 条件下,您应该进行比较,而不是赋值
  • 你弄错了,但你已经接近了!您只需要一个点击处理程序,而不是在该点击函数内部 - 构建您的逻辑!
  • Aa 并且不要像 w3schools 那样使用 onclick,而是使用正确的 Element.addEventListener()。在 MDN 等更好的 Docs 网站上了解更多信息

标签: javascript html if-statement buttonclick


【解决方案1】:

您应该为按钮添加一个事件侦听器,但首先您应该识别它。 要识别它,您必须使用document.getElementById("the_id")。请记住,我们还有其他方法可以找到元素,换句话说,我们有很多选择器(id、类、标签名称等)。

当您使用else 语句时,您没有指定其他条件。要指定其他条件,您必须使用else if,因为else 用于不在ifelse if 中的任何内容。

<h1>Welcome</h1>

Input: <input id="welcome1" type="text" />

<button id="button">Click here</button>

<script type="text/javascript">
  const btn = document.getElementById("button")
  btn.addEventListener("click", function() {
    if (document.getElementById("welcome1").value === "hi") {
      alert("Welcome");
    } else {
      alert("See you later");
    }
  })
</script>

【讨论】:

  • 我没有注意到单等号。
  • 我更正了一些其他的东西,比如一个流浪的&lt;/body&gt;&lt;h1&gt; 的格式; textContent 属性应该是 value 属性...
  • 谢谢@SebastianSimon
【解决方案2】:

欢迎

Input: <input id="welcome1" type="text" >
<button id="button">Click here</button>

<script type="text/javascript">
  
  // add eventListener to the element
  document.querySelector("#button").addEventListener("click", handleButton, false)
  
  // function handle to check
  function handleButton () { 
    
    // get the value from the input
    // use querySelector instead of getElementById
    const inputText = document.querySelector("#welcome1").value;

    // check if is the same string and the same type (string)
    if(inputText === "hi") {
      alert ("Welcome");
    } else i f(inputText == "bye") {
      alert("See you later");  
    }
  }

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • 添加说明并修复格式。代码有语法错误。
猜你喜欢
  • 2011-11-12
  • 2013-09-16
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-26
相关资源
最近更新 更多