1

私が知っている非常に基本的なことが欠けていますが、解決策が見つからないようです。

HTML 要素と Javascript 要素がどのように相互作用するかを理解するのに苦労しています。私のコードには適切な内容がいくつかありますが、まだ完全に正しいとは言えません。また、javascriptコードをhtmlファイル自体に配置することが重要なのか、それとも外部jsファイルに保持して呼び出すことができるのかどうかもわかりません。

とにかく、やることリストを作ろうとしています。したいこと: -項目を「リスト」配列に保存する -項目全体を順序付きリストに表示する -ユーザーが新しい項目をリストに追加できるようにする (インデックス ページのテキスト入力を介して)

任意のガイダンスをいただければ幸いです

私のコード:

<body>
<div id="wrapper">
<h3></h3>
    <ol id="unfinished">

    <form name="addToList">
    <li><input type="text" id="newItem"></li>
    </form>

    <li></li>

(そして私のjsファイルで)

var list = []
var newItem = document.getElementsById("newItem");
4

2 に答える 2

4

必要なものは次のとおりです。

  • 新しい todo アイテムの「入力」フィールド
  • リスト、たとえばアイテムを表示する「ol」リスト
  • 新しいアイテムをリストに追加するボタン
  • ボタンをリッスンするイベントリスナー

例として:

<ol id="listforitems">
    <li>Item that is already there</li>
</ol>
<input type="text" id="newlistitem">
<input type="button" id="buttonfornewitem" value="Add to list">

これらはすでに最初の数点です。魔法はJSに付属しています

// event listener that waits for "click" event on the button
document.getElementById('buttonfornewitem').addEventListener('click', function(e) {
    // we create a new element to append it to the list
    var newElement = document.createElement('li');
    // we define the content of the new element to be the value that has been entered in the input-field
    newElement.innerHTML = document.getElementById('newlistitem').value;
    // then we add it to the list
    document.getElementById('listforitems').appendChild(newElement);

    // optional: reset the input field so that you can add another todo-task
    document.getElementById('newlistitem').value = '';
});
于 2013-10-06T13:10:47.873 に答える