2012-10-04 34 views
0

呃,爲什麼不`噸的工作,IV採用了類似這樣的代碼爲我的網站很多times..butnow不工作..輸入按鈕的onClick刪除最接近的div

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())進行了測試,沒有發現任何東西。

enter image description here

+1

爲什麼你不因爲你已經在使用它綁定jQuery的事件處理程序?這會讓事情變得更容易。 –

+0

我的div是從客戶端和服務器端創建的。它很容易添加onclick函數而不是綁定 - 重新綁定所有新項目,不是? –

+0

@NovkovskiStevoBato你可以使用委託事件,如果你擔心它動態創建 –

回答

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 
    }); 
}); 
+0

你的編輯代碼適合我。我不知道我可以分配點擊這樣的功能:) –

1

這應該工作!

HTML

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

JQuery的

function Remove(obj){ 
    $(obj).closest('div').remove(); 
}