0

私のHTML:

<table id="laboral">
    <tr>
        <td><input type="text" name="start"/></td>
        <td><input type="text" name="end"/></td>
        <td><textarea name="desc"></textarea></td>
        <td><button type="button" onclick="saveRow(this);"> + </button></td>
    </tr>
</table>

ボタンを押す+と、最初の行とまったく同じように新しい行を作成しますが、onclickイベントは機能しません:

値を保存して 2​​ と を作成するコードは次inputtextareaとおりです。

var button = document.createElement("button");
button.type = "button";
button.setAttribute("onclick", "saveRow(this);")
button.innerHTML = "+";
var btn = tr.insertCell(3);
btn.appendChild(button);    

Firefox で結果を調べると、最初のボタンと新しく生成されたボタンのコードが同じであることがわかります。しかし、生成されたものは機能しません。

4

1 に答える 1

1

追加する可能性のあるすべてのボタンに対してイベント ハンドラーを定義するよりも、テーブルに任せた方が効率的です。この場合、次のようにします。

// this script should be placed after the table on the page, or deferred in some way
document.getElementById('laboral').onclick = function(e) {
    e = e || window.event;
    var elem = e.srcElement || e.target;
    if( !elem.tagName) elem = elem.parentNode;
    if( elem.tagName == "BUTTON") {
        var tr = elem;
        // find the row that contains the button
        while(tr.tagName != "TR") tr = tr.parentNode;
        tr.parentNode.insertBefore(tr.cloneNode(true),tr.nextSibling);
    }
};

やった^_^

于 2013-11-10T11:22:48.223 に答える