1

ええと、なぜこれが機能しないのですか、iv は私のサイトでこのような同様のコードを何度も使用しました..しかし、今は機能しません..

HTML

<div><span>a</span><input type='hidden' /> <input type='button' onClick='Remove(event)' />

JQuery

function Remove(e){
e.preventDefault();
$(this).closest('div').remove();
}

$(this) は私のボタンではないようです。私は alert($(this).val()) でテストしましたが、何も起こりませんでした。

ここに画像の説明を入力

4

2 に答える 2

4

ボタン要素にクラスを追加し、ハンドラーをボタンにバインドするのはどうですか

<div>
   <span>a</span>
   <input type='hidden' /> 
   <input type='button' class'removeDiv' />

コード:

$(function () {
    $('.removeDiv').click (function () { 
         $(this).parent().remove();
         // As I see the input is direct child of the div
    });
});

私のdivは、クライアント側とサーバー側からも作成されます。バインドを解除する代わりにonclick関数を追加するのは非常に簡単です-新しいアイテムですべてを再バインドしますか?

このような場合、委任されたイベントを使用できます。下記参照、

$(function () {
    //Replace document with any closest container that is available on load.
    $(document).on('click', '.removeDiv', function () { 
         $(this).parent().remove();
         // As I see the input is direct child of the div
    });
});
于 2012-10-04T18:28:11.170 に答える
3

これはうまくいくはずです!

HTML

<div><span>a</span><input type='hidden' /> <input type='button' onClick='Remove(this)' />

JQuery

function Remove(obj){
    $(obj).closest('div').remove();
}
于 2012-10-04T18:30:30.730 に答える