使用jQuery blur函数从输入字段返回值

Return value from input field with the jQuery blur function

本文关键字:输入 字段 返回值 函数 jQuery blur 使用      更新时间:2023-09-26

目标:用户关注输入字段。用户在输入字段中写入值。当用户完成并且输入字段不再处于焦点中时,将插入的值保存到一个名为'inputFieldValue'的变量中。这应该调用函数'returnInputValue'来完成。

<!DOCTYPE html>
<html>
    <head>
        <title>My test</title>  
    </head>
    <body>
        <input class="input" />
        <script type="text/javascript" src="jquery.min.js"></script>
        <script type="text/javascript" src="test.js"></script>
    </body>
</html>

. js

function returnInputValue() {
    var inputValue;
    $('.input').blur(function() {   
        inputValue = $('.input').val();
    });
    return inputValue;
}
var inputFieldValue = returnInputValue();

当我在插入值并再次聚焦后从控制台调用变量inputFieldValue变量时,它仍然是"未定义"。

我错过什么了吗?

您执行的函数是异步函数,也就是说,它基于input触发blur事件后的时间。您需要在blur事件中返回它:

function returnInputValue() {
    var inputValue;
    $('.input').blur(function() {   
        inputValue = $('.input').val();
        return inputValue;
    });
}
根据一些人的建议,甚至上面的代码也是不正确的。inputValue不工作,因为它总是返回undefined

或者,设置它直接访问最后的blur红色值。

var inputValue = "Not Blurred Yet!";
$('.input').blur(function() {   
    inputValue = $('.input').val();
});
function returnInputValue() {
    return inputValue;
}

这是当前的逻辑:

  1. 初始化一个undefined值的变量
  2. 绑定在未定义时刻执行的处理程序,变量仍然是undefined
  3. 立即返回undefined

以上逻辑是错误的,应该纠正。最好的选择是将最终逻辑移动到blur处理程序中:

 $('.input').blur(function() {   
    var inputValue = this.value;
    // do something with the value
    // ...
 });

如果您需要在某个节点获取值,请查询DOM,选择该元素并获取其值

尝试在函数外声明变量

    <script>
       var inputValue;
        function returnInputValue() {
        $('.input').blur(function() {   
            inputValue = $('.input').val();
        });
        return inputValue;
   }
    var inputFieldValue = returnInputValue();
    </script>

您可以使用。

$(document).on("blur","#Yourinput",function(){
   var Myval = $("#Yourinput").val();
   // Execute your code here I.e call your function 
   // ...
// You do not even have to call you function put
// It in a div to display 
$("#yourdiv").html(Myval);
//Will display it in a div
//Or add to array
Yourarray.push(Myval);
});

使用jQuery的.on()方法。

这个方法非常灵活。如果你要插入到数据库中,你也可以在这里使用jquery ajax。

你需要处理事件也就是用另一个事件代替blur但是如果你使用jquery的话我相信这是最简单的方法