简体   繁体   English

通过多个输入循环并使用jQuery将答案保存到变量

[英]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来实现这一目标吗?

You can use .map() to solve this: 您可以使用.map()解决此问题:

var userAnswer = $('.the-inputs input').map(function() {
    return $(this).val();
}).get().join(' ');
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM