2010-03-06 35 views
1

我有這樣的代碼jQuery的追加和刪除元素問題

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
<title>Test jQuery</title> 

<script type="text/javascript" src="jquery.js"></script> 

<script type="text/javascript"> 
$(function() { 
$(".add").click(function() { 
    $("#demos").append("<input type='text' size='20' name='txt[]'> <a href='#' onClick='removeFormField(); return false;'>Remove</a>"); 

return false; 
    }); 
}); 

    function removeFormField() { 
    $(this).prev("input").remove(); 
    } 


</script> 

<body> 
<a class="add" href="#">add</a> 
<div id="demos"></div> 


</body> 
</html> 

,當我按下增加其工作良好,但是當點擊刪除其未刪除任何

回答

2

您需要提供一些元素引到你的函數:

function removeFormField() { 
    $(this).prev("input").remove(); 
} 

Currenlty,$(this)沒有涉及任何內容。你應該試試這樣的:

function removeFormField(elem) { 
    elem.remove(); 
}