Javascript jQuery查找元素,然后生成逗号分隔的列表
我的页面上有许多文本框,我想在单击按钮时将这些文本框中的值添加到另一个元素中。但是,我当前的代码输出如下值:Javascript jQuery查找元素,然后生成逗号分隔的列表,javascript,jquery,Javascript,Jquery,我的页面上有许多文本框,我想在单击按钮时将这些文本框中的值添加到另一个元素中。但是,我当前的代码输出如下值: Value oneValue twoValue three var textInput = $(".random-input").text(); $(".output-box").append(textInput); 我更希望他们能像这样出来: Value one, Value two, Value three 我现在的JS是这样的: Value oneValue twoValu
Value oneValue twoValue three
var textInput = $(".random-input").text();
$(".output-box").append(textInput);
我更希望他们能像这样出来:
Value one, Value two, Value three
我现在的JS是这样的:
Value oneValue twoValue three
var textInput = $(".random-input").text();
$(".output-box").append(textInput);
问题是因为所有元素都是一起解释的。要解决此问题,您可以
map()
将文本值映射到数组并join()
它:
var textInput = $(".random-input").map(function() {
return $(this).val();
}).get().join(', ');
$(".output-box").text(textInput);
以上假设。输出框
是一个标准元素。如果它是另一个文本框,则需要使用val(textInput)
-更新日期:2020年10月-
通过使用ES6箭头函数,上述示例现在也可以变得更加简洁:
var textInput = $(".random-input").map((i, el) => el.value).get().join(', ');
$(".output-box").text(textInput);
您可以迭代每个输入,然后使用
var textInput=[];
$(“.random input”).each(函数(){
textInput.push(此.value)
});
$(“.output box”).append(textInput.join(',')代码>
@u\u mulder我做了什么问题