【问题标题】:Focus on input to display a console log message from if/if else conditional?专注于输入以显示来自 if/if else 条件的控制台日志消息?
【发布时间】:2018-01-18 03:36:48
【问题描述】:

我不知道为什么当我“关注”输入时,它不会显示我的控制台日志消息,不像它是空的或不空的,它会显示消息。我是不是用错了事件?

(只是我的部分代码,如果需要更多详细信息,请告诉我)

HTML

<input id='input' placeholder="President Name" type="text"> 

JS

function message() {
   var presidentInput = document.getElementById('input').value;
            if (presidentInput === "") {
                console.log('Please enter something in the input');
            } else if (presidentInput !== "" || document.getElementById('input').onfocus){
                console.log('Great job');   
            }
        }
message();

【问题讨论】:

  • message() 函数是如何被调用的,是通过一些事件。请添加更多详细信息
  • 您好,您需要添加一个事件监听器或者可以添加onfocus属性。示例 -
  • 您需要通过添加 onxxx="yourhandler();" 向输入元素添加事件处理程序属性以使用 addEventListerner 方法以编程方式输入或添加它。在您的示例中,您的消息函数在您调用它时只运行一次。
  • 您的代码看起来不错,唯一的问题可能是浏览器控制台,可能是您关闭了控制台,或者尝试在不同的浏览器中检查

标签: javascript if-statement events input


【解决方案1】:
var input = document.getElementById('input');

jQuery.input.focus(function(){
  if(input.value === ""){
    console.log('Please enter something in the input');
  else{
    console.log('Great job');
  }
});

也许这段代码不正确。

但是,关键是在输入标签上使用事件监听器。

input.addEventListener("focus", function(){
      if(input.value === ""){
        console.log('Please enter something in the input');
      else{
        console.log('Great job');
      }
});

【讨论】:

  • 这里包含 jQuery 可能只会让发帖者更加困惑
【解决方案2】:

只需使用 onblur 事件。 检查这个link

你没有绑定任何事件。您只是在声明后调用消息函数。这就是为什么它只记录“请在输入中输入内容”。

【讨论】:

    猜你喜欢
    • 2014-02-26
    • 2015-02-05
    • 2022-01-16
    • 2019-07-01
    • 2015-05-03
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多