javascript jQuery .val() 在设置变量时不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5327331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:49:08  来源:igfitidea点击:

jQuery .val() not working when setting a variable

javascriptjquery

提问by geoffs3310

If i have an input like so:

如果我有这样的输入:

<input type="text" id="textvalue" />

the following code will change its value:

以下代码将更改其值:

$(document).ready(function() {
    $('#textvalue').val("hello");
});

however the following will not work:

但是以下方法不起作用:

$(document).ready(function() {
    var = "hello";
    $('#textvalue').val(var);
});

Why does the second one not work? I need to be able to change the value of the textbox to the value of a variable

为什么第二个不起作用?我需要能够将文本框的值更改为变量的值

回答by Loktar

Your varstatement needs to look something like this

你的var陈述需要看起来像这样

var something = "hello"

$('#textvalue').val(something );

Right now your not actually assigning a value to a variable, and then you are trying to use the varkeyword.

现在您实际上并没有为变量赋值,然后您正在尝试使用var关键字。

Variable Reference

变量引用

回答by David says reinstate Monica

varis a reserved word, which means it can't be used as a variable name. If you try:

var是一个保留字,这意味着它不能用作变量名。如果你试试:

var variable = "hello";

$('#textvalue').val(variable);

it would work.

它会工作。

Just for interest: varis used to declarevariables, as above.

只是为了兴趣:var用于声明变量,如上。

回答by Eric Allen

var is a reserved word in JavaScript because you use it to declare a variable and you are therefore declaring an empty variable.

var 是 JavaScript 中的保留字,因为您使用它来声明一个变量,因此您声明的是一个空变量。

Use this:

用这个:

$anything = "hello";
$('#textvalue').val($anything);

Obviously you can replace anything with whatever you want, just don't use var.

显然你可以用你想要的任何东西替换任何东西,只是不要使用 var。

Naming conventions are pretty important, you should have a meaningful name for each variable, ideally.

命名约定非常重要,理想情况下,每个变量都应该有一个有意义的名称。

回答by yojimbo87

Try this:

试试这个:

$(document).ready(function() {
    var myHello = "hello";
    $('#textvalue').val(myHello);
});

You have to assign your text to a variable with name. var itself is a keyword.

您必须将文本分配给具有名称的变量。var 本身是一个关键字。