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

geo*_*310 2 javascript jquery

如果我有这样的输入:

<input type="text" id="textvalue" />
Run Code Online (Sandbox Code Playgroud)

以下代码将更改其值:

$(document).ready(function() {
    $('#textvalue').val("hello");
});
Run Code Online (Sandbox Code Playgroud)

但是以下方法不起作用:

$(document).ready(function() {
    var = "hello";
    $('#textvalue').val(var);
});
Run Code Online (Sandbox Code Playgroud)

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

Lok*_*tar 9

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

var something = "hello"

$('#textvalue').val(something );
Run Code Online (Sandbox Code Playgroud)

现在你实际上没有为变量赋值,然后你试图使用var关键字.

变量参考


Dav*_*mas 7

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

var variable = "hello";

$('#textvalue').val(variable);
Run Code Online (Sandbox Code Playgroud)

它会奏效.

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