.val()没有从输入获取更新值 [英] .val() not getting updated value from input

查看:115
本文介绍了.val()没有从输入获取更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个输入字段,我正在尝试通过单击按钮使用jquery获取其值。这似乎是一个非常简单的操作,但对于我的生活,我无法让它工作。以下是代码段:

I have two input fields, and I'm trying to get their values using jquery by clicking a button. It seems like a very simple operation, but for the life of me I can't get it to work. Here is the code snippet:

Name: <input type="text" id="name" value="test1"><br>
Message: <input type="text" id="line" value="test2"><br>
<button id="submitButton">Submit</button>

<script>
name1 = $("#name").val();
line1 = $("#line").val();

$("#submitButton").click(function(){
    alert("Name: " + name1 + "\nMessage: " + line1);
});

</script>   

如果我没有指定值,则两个变量的alert都返回undefined。如果我更改输入的值并单击按钮,它仍然会显示test1和test2。必须有一些我在这里缺少的简单,任何人都知道它是什么?

If I don't specify the value, the alert returns with undefined for both variables. If I change the values of the input and click the button, it still says test1 and test2. There has to be something simple that I'm missing here, anyone know what it is?

推荐答案

在你的代码中,你获取初始化脚本时的值,然后引用点击函数中该点的值,而不是获取当前值。

In your code, you fetch the values when the script is initialized, and then reference the value they had at that point in your click function rather than fetching the current value.

尝试:

$("#submitButton").click(function(){
    name1 = $("#name").val();
    line1 = $("#line").val();
    alert("Name: " + name1 + "\nMessage: " + line1);
});

这篇关于.val()没有从输入获取更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆