无法使用 jQuery 删除动态添加的内容
我使用 jQuery 让用户动态添加和删除表单字段,但它无法正常工作。
删除第一个字段(在 HTML 标记中硬编码)时它工作得很好,但它不允许我删除任何动态添加的字段。
这是我的 jQuery 代码:
$("#addDog").click(function(event)
{
event.preventDefault();
var doglist = <?php echo "'" . $javadogs . "'"; ?>;
var newdog = '<div><select name="resDog[]" class="select">' + doglist + '</select><input type="text" class="shortinput" name="resResult[]" size="20" value="" /><a href="#" class="deleteDog"><img src="/admin/images/delete.png" alt="Remove dog" /></a></div>';
$(this).parent().before(newdog);
});
$(".deleteDog").click(function(event)
{
event.preventDefault();
$(this).parent().remove();
});
我尝试使用 jQuery 的 .on()
函数,但这也不起作用。
I'm using jQuery to let users dynamically add and remove form fields, but it's not working properly.
It works perfectly fine when removing the first field (which is hard-coded in the HTML mark-up), but it won't let me remove any of the fields that have been added dynamically.
Here's my jQuery code:
$("#addDog").click(function(event)
{
event.preventDefault();
var doglist = <?php echo "'" . $javadogs . "'"; ?>;
var newdog = '<div><select name="resDog[]" class="select">' + doglist + '</select><input type="text" class="shortinput" name="resResult[]" size="20" value="" /><a href="#" class="deleteDog"><img src="/admin/images/delete.png" alt="Remove dog" /></a></div>';
$(this).parent().before(newdog);
});
$(".deleteDog").click(function(event)
{
event.preventDefault();
$(this).parent().remove();
});
I tried using jQuery's .on()
function, but that didn't work either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是如何使用
on
理想情况下,所有这些
deleteDog
按钮都将放置在某种容器中。如果所有这些按钮都位于 id 为foo
的 div 中,则可以更有效地设置事件,如下所示:现在,不再检查文档中任何位置的每次单击,而只检查那些按钮冒泡到
#foo
的点击次数是。我猜您最初尝试像这样使用
on
:这在功能上等同于:
像这样省略选择器参数会创建一个直接绑定事件 - 仅元素调用
on
时与.deleteDog
选择器匹配的内容将被连接。应用选择器(就像在我的原始代码中一样)使其成为委托事件,jQuery 将侦听所有点击,如果它们源自具有
deleteDog
类的元素,则函数将会触发。Here's how you want to use
on
Ideally all of these
deleteDog
buttons will be housed in some sort of container. If all of these buttons were to be in a div with an id offoo
, you would more efficiently set up the events like this:Now, instead of every click anywhere in the document being inspected, only those clicks that bubble up to
#foo
are.I'm guessing you originally tried to use
on
like this:This is functionally identical to saying:
Omitting the selector parameter like this creates a directly-bound event—only the elements that match the
.deleteDog
selector at the timeon
is called will be wired.Applying a selector—like in my original code—makes it a delegated event—jQuery will listen for all clicks, and if they originate from an element with the class
deleteDog
, the function will fire.