gpt4 book ai didi

javascript - 组合来自不同输入的字符串

转载 作者:行者123 更新时间:2023-11-30 16:13:14 25 4
gpt4 key购买 nike

我有一些带有数据属性的输入

<form>
<input style="width: 300px" data-schrift="SchriftEins" name="input1" id="input1" /></br></br>
<input style="width: 300px" data-schrift="SchriftEins" name="input2" id="input2" /></br></br>
<input style="width: 300px" data-schrift="SchriftZwei" name="input3" id="input3" /></br></br>

</form>

我需要将输入的值与相同的数据属性结合起来

我创建了一个数组 inputs 应该像这样在最后存储结果:

[SchriftEins: "from first input & from second input", SchriftZwei: "from third input "]

目前我有这样的事情:

var inputs = new Array();

$("form").on("keydown",function(e){
$("form :input").each(function(){
var schrift = $(this).data("schrift");
var value = $(this).val();
inputs[schrift] = value;
});
console.log(inputs);
});

此代码将覆盖该值我该如何解决?

非常感谢!

最佳答案

正如其他人所提到的,您可能希望使用对象而不是数组。您还需要使用 keyup,并确保您没有将新数据附加到旧数据。这样的事情应该有效:

JavaScript

var inputs = {};
//this should use keyup instead of key down
$("form").on("keyup",function(e){
//inputs needs to be reset, otherwise the next keyup will continue to append the values to old data
inputs = {};
$("input").each(function(i){
var schrift = $(this).data("schrift");
var value = $(this).val();
//if the property has already been set, append the next matching schrift, otherwise just set the property to the schrift
inputs[schrift] = inputs[schrift] == null ? value : inputs[schrift] + ' ' + value;
});
console.log(inputs);
});

一些注意事项:

  1. 将数组更改为对象,正如其他人也提到的那样。
  2. keydown 更改为 keyup,因为在 keydown 时输入的字符尚不可用,因此 inputs 变量将始终为一个字符在用户输入的内容后面
  3. 每次用户输入信息时重置inputs 对象。这可以防止循环将新数据附加到现有的旧数据。
  4. 添加了三元运算以将值附加到现有属性(如果存在)。

你可以看到它在这里工作:https://jsfiddle.net/axp1nxom/2/

希望对您有所帮助!

关于javascript - 组合来自不同输入的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35919834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com