我的页面上有很多文本框,我想在单击按钮时将它们的值添加到另一个元素中。但是,我当前的代码输出如下值:
Value oneValue twoValue three
我更希望他们这样出来:
Value one, Value two, Value three
我现在的JS是这样的:
var textInput = $(".random-input").text();
$(".output-box").append(textInput);
答案 0 :(得分:4)
问题是因为元素都被一起解释。要解决此问题,您可以map()
将文本值join()
添加到数组并var textInput = $(".random-input").map(function() {
return $(this).val();
}).get().join(', ');
$(".output-box").text(textInput);
:
.output-box
以上假设val(textInput)
是标准元素。如果是另一个文本框,则需要使用{{1}}。
答案 1 :(得分:3)
您可以遍历每个输入,然后使用join
var textInput = [];
$(".random-input").each(function() {
textInput.push(this.value)
});
$(".output-box").append(textInput.join(', '));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='random-input' value='val1' />
<input type='text' class='random-input' value='val1' />
<input type='text' class='random-input' value='val1' />
<input type='text' class='random-input' value='val1' />
<input type='text' class='random-input' value='val1' />
<input type='text' class='random-input' value='val1' />
<input type='text' class='random-input' value='val1' />
<div class='output-box'></div>
&#13;
答案 2 :(得分:0)
@Rory McCrossan 代码移至 jQuery 函数 joinVal:
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
try (OutputStream os = new FileOutputStream("report.xls")) {
Row row;
Cell cell;
row = sheet.createRow(0);
cell = row.createCell(0);
cell.setCellValue("Shop:");
cell = row.createCell(1);
cell.setCellValue(4);
cell = row.createCell(6);
cell.setCellValue("Export Date:");
cell = row.createCell(7);
cell.setCellValue("14.06.2019");
// -----
row = sheet.createRow(2);
cell = row.createCell(0);
cell.setCellValue("Code Supervisor:");
cell = row.createCell(1);
cell.setCellValue(4);
cell = row.createCell(6);
cell.setCellValue("Audit Date:");
cell = row.createCell(7);
cell.setCellValue("dd.MM.yyyy");
//----
row = sheet.createRow(4);
cell = row.createCell(6);
cell.setCellValue("Shop Note:");
cell = row.createCell(7);
cell.setCellValue("Note something");
wb.write(os);
}catch(Exception e) {
System.out.println(e.getMessage());
}
用法:
jQuery.fn.extend({
joinVal: function (separator)
{
if (typeof separator === 'undefined')
separator = ",";
var $this = $(this);
if ($this && $this.length > 1)
return $this.map(function () { return $(this).val(); }).get().join(separator);
else
return $this.val();
}
});