jquery追加并删除元素问题

时间:2010-03-06 18:22:23

标签: 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>

当我按下添加其工作正常,但点击删除它不删除任何东西

1 个答案:

答案 0 :(得分:2)

您需要为您的函数提供一些元素参数:

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

目前,$(this)并未提及任何内容。你应该尝试这样的事情:

function removeFormField(elem) {
  elem.remove();
}
相关问题