从 .focusout() 的输入中检索 .val()

Retrieve .val() from inputs on .focusout()

我有一系列动态生成的输入,具有相同的class,例如:

<input class="addressitem" type="text"/>
<input class="addressitem" type="text"/>
<input class="addressitem" type="text"/>

用户在每个字段中输入数据后,我想获取该数据并将其放入隐藏输入的值字段中。

但是,我无法找到执行此操作的最佳方法。到目前为止我已经尝试过:

$(".addressitem").focusout(function() {
    var addressinput = $(this).val();
    console.log(addressinput);
});

$(".addressitem").change(function() {
    var addressinput = $(this).val();
    console.log(addressinput);
});

但是我无法在控制台中显示任何内容。

谁能指出我正确的方向?

只要您在 document.ready 事件中定义它们并且您的页面中没有任何其他脚本错误,您的两种方法都应该有效。

$(function(){

   $(".addressitem").change(function() {
    var addressinput = $(this).val();
    console.log(addressinput);
   });

   $(".addressitem").focusout(function() {
    var addressinput = $(this).val();
    console.log(addressinput);
   });

});

您可以使用浏览器控制台验证页面中是否存在其他脚本错误。

另请记住,change 事件在焦点离开时在文本输入字段上发生。因此,当用户从文本框更改焦点时,您会看到 console.log。如果你想要即时更新,你应该考虑使用 keyUp 事件

Here 是工作样本。


编辑:根据评论我有Jquery点击功能生成的字段。我必须在点击功能中移动我的代码才能正常工作。

不,你不需要。您可以简单地使用 jQuery on 委托方法。当您使用 jQuery on 注册事件处理程序时,它将适用于 DOM.

中的当前和未来元素(动态注入)

因此您的代码将是

$(function(){

   $(document).on("change",".addressitem",function() {
     var addressinput = $(this).val();
     console.log(addressinput);
   });     

});

这可能是最佳选择,正如您所说,它们是动态生成的输入。

$(document).on("blur",".addressitem",function() {
    var addressinput = $(this).val();
    console.log(addressinput);
});

WORKING FIDDLE

检查你的控制台

在 HTML5 中的 focusout 如下:

<input type="text" onfocusout="makeITUpperCase(this)">

并且在 javascript 中如下:

function makeITUpperCase(e) {
  console.log(e.value);
  e.value = e.value.toUpperCase();
}

该函数将'this'对象作为e,可用于获取值或改变