Jquery :如何在客户端存储文本框值并显示?

Jquery :How to store textbox value clientside and display?

下面的代码将在单击按钮时更新用户在文本框中输入的显示值,但在此代码中它不会保留用户先前输入的值。

<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />    
<button id="Get">Submit</button> 
<div id="textDiv"></div> - 
<div id="dateDiv"></div>
jQuery(function(){
    $("button").click(function() {
        var value = $("#txt_name").val(); 
        $("#textDiv").text(value);
        $("#dateDiv").text(new Date().toString());
    });
});

现在我想保留用户输入的所有值,当用户提交按钮时显示以前和当前的值。

如何实现?

下面的代码将有助于保留所有值

var $input = $('#inputId');    
$input.data('persist', $input.val() );

如果是,当用户点击按钮时如何显示所有以前的值、当前值等?

如果我没猜错,这就是你需要的?

<h1>Type your comment below </h1>

<input id="txt_name" type="text" value="" />

<button id="Get">Submit</button> 

<script type="text/javascript">
    jQuery(function(){
    $("button").click(function() {
      var value = $("#txt_name").val(); 
      $("#section").prepend('<div class="textDiv">'+value+'</div>')
      $("#section").prepend('<div class="dateDiv">'+new Date().toString()+'</div>')
      $("#txt_name").val('');
    });
});
</script>

<!-- each time you press submit, a new line will be pushed here -->
<div id="section">
</div>

如果只想显示用户提交的之前和当前值并使用数据功能,则:

$("button").click(function() {
    var input = $("#txt_name").val(); 
    var previous = $("#textDiv").data('previous') || '';
    $("#textDiv").text(previous+input);
    $("#textDiv").data('previous',input);
    $("#dateDiv").text(new Date().toString());
});

如果您想要所有的值并存储它们,那么我会创建一个数组。但您始终可以连接字符串。

var arr = [];
$("button").click(function() {
    var input = $("#txt_name").val();
    arr.push(input);
    var previous = $("#textDiv").data('previous') || '';
    $("#textDiv").text(previous+input);
    $("#textDiv").data('previous',previous+input);
    $("#dateDiv").text(new Date().toString());
});

不使用 .data() 你可以这样做:

 $("button").click(function() {
    var input = $("#txt_name").val(); 
    $("#textDiv").text($("#textDiv").text()+input);
    $("#dateDiv").text(new Date().toString());
});

您可以使用单个 div.

,而不是对消息和日期使用两个单独的 div
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<div id="msgDiv"></div>

$(document).ready(function() {
  var preservedTxt = '';
  $("button").click(function() {
       var input = $("#txt_name").val();
       var date = new Date().toString();
       var msg = input + ' - ' + date;

       preservedTxt = preservedTxt + '<br>' + msg;

       $('#msgDiv').html(preservedTxt);
   });
});

Jsfiddle : https://jsfiddle.net/nikdtu/p2pcwj2f/

将值存储在数组中会有所帮助

    jQuery(function(){
var name=[];
var time=[];
    $("button").click(function() {
        var value = $("#txt_name").val(); 
        name.push(value);
        $("#textDiv").text(name);
        time.push(new Date().toString())
        $("#dateDiv").text(time);

    });
});