【问题标题】:Saving an input value into a variable as you type, or as soon as the input loses focus在您键入时或输入失去焦点时将输入值保存到变量中
【发布时间】:2013-03-15 02:24:20
【问题描述】:

我已经研究这个问题一段时间了,我提出的每个解决方案“几乎都有效”。理想情况下,我想在键入时将输入值保存到变量中,因此在将输入值保存到变量之前我不必执行任何命令。由于我找不到解决方案,所以我一直在努力在输入失去焦点后立即对其进行更改。我试过 .focusout、.change 和 .blur,但在输入失去焦点的那一刻,没有一个真正改变它。

//This will save the input value into the variable formInput
var formInput = $("#someForm input[type=text]").val();

//This successfully changes the value of formInput, but only after performing 
//another command, such as clicking go or pressing enter.  
//Tab does not count to the input "losing focus"

$("#someForm input[type=text]").focusout(function() {
$(this).val() = formInput.val();
});

// Same as focusout, as well as blur.
$("#someForm input[type=text]").change(function() {
$(this).val() = formInput.val();
});

//Nope.
$("#someForm input[type=text]").keyup(function() {
    formInput = $("this").val();
});

【问题讨论】:

  • 你想要$(this).val(formInput.val()); 吗?但这会替换您刚刚输入的内容。
  • 我真的没有达到你的目标。您正在尝试自行替换输入的值?
  • @dystroy 我正在尝试将输入的值保存到变量 formInput 中,无论是在输入时(动态保存)还是在光标不再位于输入字段中时(由于某种原因,这似乎不是 focusout 的工作方式。)后来,输入中的确切文本被放置到 URL 作为搜索词。问题是变量没有被保存,直到我在中间执行某种命令,例如按表单附带的“Go”按钮,或者在输入后按 Enter。

标签: javascript input var


【解决方案1】:

在现代浏览器中,listen to the input event:

$("#someForm input[type=text]").on("input", function() {    
    formInput = $(this).val();
});

但是,如果您弄清了 formInput 是包含字段值的字符串值还是链接到字段本身的 jQuery 对象(如果 formInput 是字符串),keyup 处理程序也应该可以工作,它不会有val() 方法)。

还有这段代码:

$("this")

正在选择所有 <this> 元素,如果返回任何内容,我会感到惊讶。

【讨论】:

  • 感谢您对 $(this) 与 $("this") 的提醒,我很快就会更多地使用您的代码,到目前为止我还没有运气。再次感谢您的帮助。
【解决方案2】:

试试

var inputText;
$("#someForm input[type=text]").keyup(function() {
    inputText = $(this).val();
});

【讨论】:

  • 感谢您的回答。这个答案实际上使我的变量未定义。
猜你喜欢
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 2021-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多