admin管理员组文章数量:1332890
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
2 Answers
Reset to default 4How 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();
}
本文标签: javascriptInput button onClick remove closest divStack Overflow
版权声明:本文标题:javascript - Input button onClick remove closest div - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742315057a2451648.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论