[英]Loop through multiple inputs and save the answer to a variable using jQuery
So far, I have: 到目前为止,我有:
$('.the-inputs input').each(function() {
userAnswer = $(this).val();
});
However, if I console.log
this out, it comes out on separate lines (is this an array?) I would like it as a string. 但是,如果我将console.log
注销,它会以单独的行出现(这是数组吗?),我希望将其作为字符串。
So, if the user enters "Hello" "World" in the two inputs, I want the variable userAnswer = "Hello World"
. 因此,如果用户在两个输入中输入“ Hello”“ World”,则需要变量userAnswer = "Hello World"
。
I also need the variable accessible outside the function. 我还需要在函数外部可访问的变量。 Am I right in leaving off the var
to achieve this? 我可以放弃var
来实现这一目标吗?
var userAnswer = '';
$('.the-inputs input').each(function() {
userAnswer += $(this).val() + ' '; // add to string
});
userAnswer = $.trim(userAnswer);
console.log(userAnswer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.