2016-08-16 15 views
1
var container = document.createElement("lastExp"); 
    container.innerHTML = 'html code new form field'; 
    document.getElementById("lastExp").appendChild(container); 

クリックすると簡単なフォームが追加されます。 質問:私は私のフォーム上でこの余分なフィールドを失わない方法をページをリフレッシュするとき。jsで余分なフィールドを追加する方法

+1

クッキーまたはのlocalStorage - フロントエンド。 –

+0

私は少し誇張していました。フードの下では、ページが読み込まれるたびにその要素を追加する必要があります。 –

答えて

1

スタックオーバーフローはコードを書く場所ではありませんが、OPの必要性がある場合はここにあります。

これは最小の例です。開始するには、localStorageを使用してください。前述したように、フードの下では、ページが読み込まれるたびにその要素を追加する必要があります。

ここではスニペットが機能しません。残念ながら、iframeはサンドボックスになっているためです。実験するにはmy hubに向かいます。

var container = document.getElementById('container'), 
 
    toggle = document.getElementById('toggle'); 
 
    element = null; 
 

 
// initial check 
 
init(); 
 

 
// add click event and listen for clicks 
 
toggle.onclick = function() { 
 
    // both cases will update localStoage _inputIsThere 
 
    // if element is null -- doesn't exists, then add it 
 
    if (element == null) { 
 
    add(); 
 
    } else { 
 
    // remove the element 
 
    remove(); 
 
    } 
 
} 
 

 
// check if key exists in localStorage; this is where all the "magic" happens. 
 
function init() { 
 
    var exists = localStorage.getItem('_inputIsThere'); 
 
    if (exists && exists == 'true') { 
 
    add(); 
 
    } 
 
} 
 

 

 
function remove() { 
 
    element.remove(); 
 
    element = null; 
 
    // update key in localStorage to false 
 
    localStorage.setItem('_inputIsThere', false); 
 
} 
 

 
// adds the input and updates 
 
function add() { 
 

 
    var e = document.createElement('input'); 
 
    e.type = 'text'; 
 
    element = e; 
 
    container.appendChild(e); 
 
    // update key in localStorage to true 
 
    localStorage.setItem('_inputIsThere', true); 
 

 
}
<button id="toggle">Add/Remove</button> 
 
<div id="container"></div>

関連する問題