结合来自不同输入的字符串

时间:2016-03-10 14:52:04

标签: javascript

我有一些数据属性的输入

<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);
});

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

非常感谢!

3 个答案:

答案 0 :(得分:2)

与其他人提到的一样,您可能希望使用对象而不是数组。您还希望使用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. 添加了三元操作,以便将值附加到现有属性(如果存在)。
  5. 您可以在此处看到它:https://jsfiddle.net/axp1nxom/2/

    希望有所帮助!

答案 1 :(得分:0)

我想你想在那里使用一个不是数组的对象。

尝试像这样定义变量输入:

var inputs = {};

你会看到你想要的结果。有关对象的更多信息:https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object

如果你真的想要一个数组将不得不使用.push来添加。您可以在此处查看有关数组的更多信息https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array

编辑:我也看到2个输入具有相同的数据 - schrift值&#34; SchriftEins&#34;。这将覆盖另一个。

答案 2 :(得分:0)

你正在覆盖价值。你想要它听起来像是一个字典类型的对象。如果您想要一个数组,请尝试以下操作:

var inputs = new Array();

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

或者如果你想要一个带有命名键和值的字典:

var obj = {
key1: value1,
key2: value2
};

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

然后使用它如下:

 var myValue = obj[schrift];

希望这有助于你所需要的。