最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Input button onClick remove closest div - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Oct 4, 2012 at 18:25 Novkovski Stevo BatoNovkovski Stevo Bato 1,0432 gold badges24 silver badges56 bronze badges 3
  • 1 Why don't you bind the event handler with jQuery since you're already using it? That would make things much easier. – James Allardice Commented Oct 4, 2012 at 18:26
  • 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? – Novkovski Stevo Bato Commented Oct 4, 2012 at 18:28
  • @NovkovskiStevoBato you can use delegated events if you are worried about it being created dynamically – Selvakumar Arumugam Commented Oct 4, 2012 at 18:29
Add a ment  | 

2 Answers 2

Reset to default 4

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

This should work!

HTML

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

JQuery

function Remove(obj){
    $(obj).closest('div').remove();
}
发布评论

评论列表(0)

  1. 暂无评论