输入按钮 onClick 删除最近的 div [英] Input button onClick remove closest div

查看:24
本文介绍了输入按钮 onClick 删除最近的 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

呃,为什么这不起作用,我的网站多次使用类似的代码..但现在不起作用..

HTML

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

JQuery

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

看起来 $(this) 不是我的按钮.我用 alert($(this).val()) 进行了测试,没有任何结果.

解决方案

如何给按钮元素添加一个类,并为按钮绑定一个处理程序

<span>a</span><输入类型='隐藏'/><input type='button' class'removeDiv'/>

代码:

$(function () {$('.removeDiv').click (function () {$(this).parent().remove();//如我所见,输入是 div 的直接子级});});

<块引用>

我的 div 也是从客户端和服务器端创建的.添加 onclick 功能而不是在新项目上取消绑定-重新绑定要容易得多,不是吗?

在这种情况下,您可以使用委托事件.见下文,

$(function () {//用加载时可用的任何最近的容器替换文档.$(document).on('click', '.removeDiv', function () {$(this).parent().remove();//如我所见,输入是 div 的直接子级});});

Erm, why this don`t work, iv used similar code like this for my site many times..butnow dont work..

HTML

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

JQuery

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

Looks like $(this) is not my button. I tested with alert($(this).val()) and nothing heppend.

解决方案

How about adding a class to the button element and bind a handler to the button

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

Code:

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

My divs are created from clientside and serverside too. Its much easy to add onclick function instead to unbind-rebind all on new item, no?

In such cases you can use delegated events. See below,

$(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
    });
});

这篇关于输入按钮 onClick 删除最近的 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆