0

私は単純なjqueryコードを実装しようとしています.1つの関数はテーブルに新しい行を追加します:

function add_row(){
$('#giants_table tr:last').before('<tr><td><input type="text" name="giants_#" id="giants_#"><input type="button" id="removebtn" value="Remove row" onclick="remove_row()"</td></tr>')}

そして、その行を削除する 2 番目の関数:

function remove_row(){
$(this).parents('tr').remove()}

最初の関数は問題なく動作しますが、2 番目の関数では「this」セレクターが設定されていないようです。

何か案は?

4

3 に答える 3

1

これは 2 つの方法で実行できます

  1. this関数呼び出しを渡します。

    function add_row(){
        $('#giants_table tr:last').before('<tr><td><input type="text" name="giants_#" id="giants_#"><input type="button" id="removebtn" value="Remove row" onclick="remove_row(this)" /></td></tr>');
    }
    
    function remove_row(ele){
        $(ele).parents('tr').remove();
    }
    
  2. クリックをバインドして使用する$(this)

    function add_row(){
        $('#giants_table tr:last').before('<tr><td><input type="text" name="giants_#" id="giants_#"><input type="button" id="removebtn" class="removebtn" value="Remove row" onclick="remove_row(this)"/></td></tr>');
        $('#giants_table tr td .removebtn').unbind('click').bind('click', function() {
              $(this).parents('tr').remove();
        });
    }
    

私は確かに2番目のオプションに行きたいと思います。

于 2013-09-24T11:28:28.390 に答える
1

イベント ハンドラーをインラインで (つまり、HTML コード内で) 登録すると、パラメーターは設定されません。thisグローバル ( window) オブジェクトに設定されます。

1 つのオプションはthis、パラメーターとしてに渡すremove_rowことですが、jQuery を使用して、1 回限りの単一の委任されたイベント ハンドラーを作成する方がはるかに優れています。

$('#giants_table').on('click', 'button', remove_row);

onclickその後、HTML コードで属性を完全に省略できます。これは「委任された」ハンドラーであるため、イベントの登録時に存在しない場合でも、テーブルに追加されたすべての行で自動的に機能します。

インラインで行うのではなく、jQuery を使用してイベントを登録する主な利点は次のとおりです。

  1. の自動設定this
  2. オブジェクトの通過を保証event(初期の MSIE バージョンとは異なります)
  3. eventブラウザの違いを取り除くためのオブジェクトのプロパティの正規化
于 2013-09-24T11:29:28.210 に答える
0

ハンドラーを委任するclickか (おそらくより良い解決策)、行を作成するときにハンドラーを割り当てることができます。以下に例を示します (HTML マークアップの代わりに DOM 要素の作成を使用します。より良い方法です)。

// delegate the function once in your DOM.ready
$('#giants_table tr').on('click', 'input[type="button"][value="Remove Row"]', function (e) {
    $(this).parents('tr').remove(); // this will point to the input
});

// or assign it when you create the row
function add_row(){
    var input = $('<input />'), //create new DOM elements
        row = $('<tr />'),
        cell = $('<td />'),
        rowCount = $('#giants_table tr').length;
    $('#giants_table tr:last').before(tr.append(td.append(input.clone().attr({
        "id": "giants_" + rowCount,
        "name": "giants_" + rowCount,
        "type": "text"
    })).append(input.clone().attr({
        "id": "removeRow" + rowCount,
        "type": "button",
        "value": "Remove Row"
    }).click(function (e) {
        $(this).parents('tr').remove(); // this now points to the input
    }))));
}
于 2013-09-24T11:35:33.347 に答える