2016-08-16 111 views
0

我想添加一個日期(也顯示給用戶)到我正在工作的Web應用程序中的用戶的每個列表輸入。如何將當前輸入日期添加到動態列表?

這是我的HTML代碼

<div id="todo"> 
    <header> 
     <h1>To-Do List</h1> 
     <input id="new-todo" type="text" placeholder="Things you need to do..."> 
    </header> 

    <section id='main'> 
     <ul id='todo-list'></ul> 
    </section> 
</div> 

和JavaScript是這裏

$(document).ready(function() { 
     function runBind() { 
     $('.destroy').on('click', function(e) { 
      $currentListItem = $(this).closest('li'); 

      $currentListItem.remove(); 
     }); 

     $('.toggle').on('click', function(e) { 
      var $currentListItemLabel = $(this).closest('li').find('label'); 

      if ($currentListItemLabel.attr('data') == 'done') { 
       $currentListItemLabel.attr('data', ''); 
       $currentListItemLabel.css('text-decoration', 'none'); 
      } 
      else { 
       $currentListItemLabel.attr('data', 'done'); 
     $currentListItemLabel.css('text-decoration', 'line-through'); 
      } 
      }); 
     } 

    $todoList = $('#todo-list'); 
    $('#new-todo').keypress(function(e) { 
    if (e.which === EnterKey) { 
      $('.destroy').off('click'); 
      $('.toggle').off('click'); 
      var todos = $todoList.html(); 
     todos += ""+ 
       "<li>" + 
      "<div class='view'>" + 
      "<input class='toggle' type='checkbox'>" + 
      "<label data=''>" + " " + $('#new-todo').val() + "</label>" + 
      "<a class='destroy'></a>" + 
      "</div>" + 
     "</li>"; 

     $(this).val(''); 
     $todoList.html(todos); 
     runBind(); 
     $('#main').show(); 

    }}); 
}); 

我應該在代碼添加到實現這一目標? 謝謝。

+0

使用'日期()'來得到當前的日期和時間。 – Barmar

回答

0

至於有人建議,得到當前的日期,然後你可以使用任何一種:new Date().toDateString();

爲了得到一個自定義日期日期格式功能(或自己製作):

  • toString()給出Tue Aug 16 2016 00:05:20 GMT-0400 (Eastern Daylight Time)
  • toDateString()Tue Aug 16 2016
  • toLocaleDateString()8/16/2016
  • 您還可以使用.getDate().getMonth().getYear()

我也建議使用jQuery創建列表項,而不是原始的HTML。例如,如果您的待辦事項名稱中包含<,您將遇到問題,因爲它未被轉義。

"<li>" + 
"<div class='view'>" + 
"<input class='toggle' type='checkbox'>" + 
"<label data=''>" + " " + $('#new-todo').val() + "</label>" + 
"<a class='destroy'></a>" + 
"</div>" + 
"</li>" 

可以變成

$('<li>').append(
    $('<div>').addClass('view').append(
    $('<input>').addClass('toggle').attr('type', 'checkbox') 
).append(
    $('<label>').attr('data', '').text($('#new-todo').val()) 
).append(
    $('<a>').addClass('destroy') 
) 
) 
0

爲了讓你可以使用內置的Date對象的JavaScript字符串的日期。

例如:

爲了得到今天的日期:使用new Datenew Date('01/01/1970').toDateString();

相關問題