[英]jQuery: write variable between 2 quotation mark
I want to create a loop for input so that the variable img get number 1 to 5 like this: 我想为输入创建一个循环,以使变量img像这样获得1到5的数字:
img1, img2 ... img5.
How to write $i
after img? img之后如何写
$i
?
for ($i=1;$i<=5;$i++) {
function(data) { $('input[name="img1"]').val(data) });
}
Note: img is between two quotation mark. 注意: img在两个引号之间。
it's edite: 它的编辑:
user = $('input[name="name"]').val();
for (var i = 1; i <= 5; i++) {
$.post("test.php", { name: user, num: i },
function(data) {
$('input[name="img'+i+'"]').val(data)
});
}
The function you have declared in your loop seems weird. 您在循环中声明的函数似乎很奇怪。 That's not valid javascript.
那不是有效的javascript。 You may try the following:
您可以尝试以下方法:
for (var i = 1; i <= 5; i++) {
$('input[name="img' + i + '"]').val(data);
}
or if we suppose that you have defined some function: 或者如果我们假设您已经定义了一些功能:
var foo = function(data, index) {
$('input[name="img' + index + '"]').val(data);
}
you could invoke it like this: 您可以这样调用它:
for (var i = 1; i <= 5; i++) {
foo('some data ' + i, i);
}
UPDATE: 更新:
An interesting example was provided in the comments section: 评论部分提供了一个有趣的示例:
for (var i = 1; i <= 5; i++) {
$.post(
"test.php",
{ name: username, num: i },
function(data) {
$('input[name="img'+i+'"]').val(data);
}
);
}
This won't work because the i variable might have changed value between the loop and the AJAX success callback. 这将不起作用,因为i变量可能已更改了循环和AJAX成功回调之间的值。 To fix this you may try the following:
要解决此问题,您可以尝试以下操作:
for (var i = 1; i <= 5; i++) {
(function(index) {
$.post(
"test.php",
{ name: username, num: index },
function(data) {
$('input[name="img'+index+'"]').val(data);
}
);
})(i);
}
or use the $.ajax()
method which allows you to pass a context to the success
callback: 或使用
$.ajax()
方法允许您将上下文传递给success
回调:
for (var i = 1; i <= 5; i++) {
$.ajax({
url: 'test.php',
type: 'POST',
data: { name: username, num: i },
context: i, // here we are defining the context
success: function(result) {
// since we have used the context parameter, this variable
// here will point to the value that i had when we initiated
// the AJAX request
$('input[name="img' + this + '"]').val(result);
}
});
}
Like this: 像这样:
for ($i=1;$i<=5;$i++) {
function(data) { $('input[name="img' + $i + '"]').val(data) });
}
By the way, I'm guessing you'e coming from a PHP background, but in JavaScript it is not conventional to use $ for variable names (except sometimes for jQuery objects). 顺便说一句,我猜您来自PHP背景,但是在JavaScript中,使用$作为变量名不是常规做法(有时用于jQuery对象除外)。 So normally you'd write your code like this:
因此,通常您会这样编写代码:
for (i=1;i<=5;i++) {
function(data) { $('input[name="img' + i + '"]').val(data) });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.