单击按钮动态添加数组中的项目

时间:2018-04-06 02:42:28

标签: jquery html

我有一个文本框和一个按钮所以基本上当我点击按钮时,文本框上写的任何内容都应该添加到一个数组中

       <input id"item" type="text">
      <input id"clickme" type="submit">
        $('#send-btn').click(function() { 
     var = item    $("#item").val()
  var itemofarrays[] ???
//add this items to an and then  display them
alert(itemofarrays)
    });
当我在输入框中输入内容时,我无法添加到数组中,请帮助

5 个答案:

答案 0 :(得分:0)

也许你正在寻找的东西

$('#send-btn').click(function() { 
    var item =  $("#item").val();
    //add this items to an and then  display them
    itemofarrays.push(item);
    $('#showItem').val(itemofarrays.join(','));
});

答案 1 :(得分:0)

尚未测试此代码,但它应该是:

var itemofarrays = [];
$('#send-btn').click(function() { 
   var item;  
   item = $("#item").val();
   //add this items to an and then  display them
   itemofarrays.push(item);
   alert(itemofarrays);
});

答案 2 :(得分:0)

<pre>
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>My First JavaScript</h2>
    <input id="item" type="text">
    <input id="send-btn" type="submit">
    <script>
        var itemofarrays=[];
        $('#send-btn').click(function() { 
            var item =   $("#item").val();
            itemofarrays.push(item);
            //add this items to an and then  display them
            alert(itemofarrays);
       });
    </script>
</body>
</html> 
</pre>

答案 3 :(得分:0)

要获得预期的结果,请使用split()方法的以下选项,该方法将拆分输入的文本,它将是可以分配给itemofarrays的数组

需要在代码中修复的语法错误很少,

1.对于点击事件使用相同的id,即clickme而不是send-btn
2. &#34; =&#34; 缺少ID值, id&#34; item&#34; id =&#34; item& #34; ID&#34; clickme&#34; id =&#34; clickme&#34;

&#13;
&#13;
  var itemofarrays=[]

$('#clickme').on('click',function() { 
     var item =  $("#item").val()
     itemofarrays = item.split('')
console.log(itemofarrays)
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="item" type="text">
      <input id="clickme" type="submit">
&#13;
&#13;
&#13;

答案 4 :(得分:0)

经过测试和工作

<!DOCTYPE html>
<html>
    <head>
        <title>Try jQuery Online</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

        <script>

        $(document).ready(function() {

            var itemofarrays = [];

           $('#clickme').click(function() { 

             itemofarrays.push($("#item").val());
             $("#result").val(itemofarrays);
             $("#item").val('')
            });
        });

        </script>

    </head>
    <body>
        <input id="item" type="text"/>
        <input id="clickme" type="submit"/>
        <br/>
        <br/>
        <input id="result" type="text" readonly="true"/>
    </body>
</html>