0

ボタンを押すたびAdd another fieldにテキストフィールドを作成するボタンが欲しいのですが。<input type="text" name="pet">

私は現在このコードを持っています:

<html>
<head>
<script>    
function add_field() 
{
  document.write( '<input type="text" name="pet">' );
};
</script>
</head>
<body>

<form name="input" method="get">
Favourite pets:<br> 
<input type="text" name="pet">
<button type="button" onclick="add_field()">Add another field</button><br>
<input type="submit" value="Submit"><br>
</form>

</body>
</html>

しかし、Add another fieldボタンを押すと、テキストフィールドしかないページが表示され、他のすべてのコンテンツが表示されなくなります。別のテキストフィールドを追加している間、他のhtmlコンテンツを保持するにはどうすればよいですか?

4

1 に答える 1

1

この行:

document.write( '<input type="text" name="pet">' );

ドキュメント全体を挿入されたマークアップに置き換えます。入力フィールドを追加する場合は、追加するフォームを見つけて、入力フィールドを作成して追加する必要があります。次のようなものを試してください:

var form = document.getElementsByTagName('form')[0],
    input = document.createElement('input');

input.setAttribute('type', 'text');
input.setAttribute('name', 'pet');
form.appendChild(input);

inputこれにより、フォームの最後にが挿入されます。insertBefore入力フィールドを必要な場所に配置するなど、他の方法を使用できます。

または、jQueryを使用します。

于 2012-10-01T12:54:53.717 に答える