【问题标题】:HTML Input Field to Javascript Function to ConsoleHTML 输入字段到 Javascript 函数到控制台
【发布时间】:2016-11-09 11:51:59
【问题描述】:

我正在尝试将输入字段中的输入回显到控制台,但无法在 HTML 字段之外打印输入,这里是一个示例:

function getInput(input) {
	var input = document.getElementById("EchoInput").value;
  console.log(input);
}

//These are the "external" inputs I'd like to print in the console.
getInput("test");
getInput("one");
getInput("two");
<input type="text" id="EchoInput" onblur="getInput()">

如您所见,它使用document.getElementById("EchoInput").value; 确实可以工作,但是在使用“test”、“one”和“two”输入测试函数时,它不起作用。

我是代码的超级新手,但我认为这里存在变量范围的问题,getElementById().value; 正在接管底部的三个函数。

打印底部函数的另一种替代方法是删除事件处理程序,但会为字段undefined 输入,这违背了目的。

有没有办法同时接受两个输入?

非常感谢您的帮助,我在这里寻找答案并找到了使用 JQuery 或我不理解的类似高级解决方案的解决方案,如果这是一个反复出现的问题,我们深表歉意。

干杯。

K.

【问题讨论】:

  • 看看$( document ).ready(function() { });
  • @HappyCoding jQuery 不是解决方案
  • 这里不需要jquery
  • @Robiseb,看看正确答案。 jQuery 是解决方案 ;)
  • @HappyCoding,你在哪里看到了一些 jQuery?

标签: javascript html scope event-handling


【解决方案1】:

您可以使用“自调用函数”来调用getInput,而且您不需要document.GetElementById 语句。

只需使用onblur="getInput(this.value)"

<input type="text" id="EchoInput" onblur="getInput(this.value)">

Javascript

function getInput(input) {
  console.log(input);
}

(function() {
  //These are the "external" inputs I'd like to print in the console.
  getInput("test");
  getInput("one");
  getInput("two");
})();

function getInput(input) {
  console.log(input);
}
  
(function() {
  //These are the "external" inputs I'd like to print in the console.
  getInput("test");
  getInput("one");
  getInput("two");
})();
&lt;input type="text" id="EchoInput" onblur="getInput(this.value)"&gt;

【讨论】:

  • 非常感谢 Nikhil,这绝对是我想要的,我担心需要更多代码来解决这个问题 ;) Robiseb & ArturN > 也谢谢你们,很高兴看到其他版本解决方案,我可以看到如何在不同的上下文中使用它们。
  • 很高兴它有帮助..干杯:)
【解决方案2】:

你可以做这样的事情:

function getInput(input) {
  var value = input || document.getElementById("EchoInput").value;
  console.log(value);
}

如果输入未定义(事件调用),您将从字段中获取值。如果输入是给定的(纯函数调用),给定的值将被打印出来。

【讨论】:

    【解决方案3】:

    问题是当您的页面加载时您的输入值为空。
    使用默认值进行测试,您将看到您的三个函数调用记录了该值。

    getInput 函数中,将输入 ID (string) 设置为参数。如果元素存在,函数将返回值。

    function getInput(elementId) {
      var element = document.getElementById(elementId);
      var input = element ? element.value : '';
      console.log(input);
    }
    
    //These are the "external" inputs I'd like to print in the console.
    getInput("EchoInput");
    getInput("");
    getInput("test");
    &lt;input type="text" id="EchoInput" onblur="getInput(this.id)" value="test"&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 2015-09-21
      • 2011-05-16
      • 2021-12-02
      • 1970-01-01
      相关资源
      最近更新 更多