event.preventDefault vs event.stopPropagation
有人能解释一下event.preventDefault()和event.stopPropagation()的区别吗?
我有一张桌子,在那张桌子里我有一个img标签。
当我点击img标签时,我想看到一个弹出窗口。
但我也希望停止选择多行,因此我使用:
1 2 3
| $("table.items tbody tr").click(function(event) {
event.stopPropagation();
}); |
当我使用JS代码时,弹出窗口不会出现;
如果我删除JS代码,弹出窗口就会工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| $(".info").live("click",function(e){
//console.log('ok');
e.stopPropagation();
var elem = $(this);
var id = $(this).attr("id").replace("image_","container_");
$('#'+id).toggle(100, function() {
if($(this).css('display') == 'block') {
$.ajax({
url:"$url",
data: { document_id:elem.attr('document_id') },
success: function (data) {
$('#'+id).html(data);
}
});
}
});
}); |
为什么?
- 这将帮助你davidwalsh.name/JavaScript事件
- 请显示你的HTML结构,所以我们知道图像是一个关系到表结构
- 它太晚停止位置的选择上mousedownclick;使用。
我不是javascript专家,但据我所知:
stopPropagation用于确保事件不会在链上冒泡。例如,单击
标记也会在其父级
上触发单击事件,然后在其父级
上触发单击事件。stopPropagation可防止这种情况发生。preventDefault用于停止元素的正常操作,例如,链接上的单击处理程序中的preventDefault将停止跟踪链接,或者单击提交按钮将停止提交表单。
- @crisimilnumereano your comment makes no sense.Sevenesaat's answer look 100%correct to me and can be checked with the answer s on the dup question as well as with the JQERY documentation for event.preventdefault(……)and event.stopprogation(……)。
- Stopprogation does stop the capture phase?
- I think the confusion around these two functions(three if you count EDOCX1 universal 0)is a doubt about whether stopping promotion automatically prevents default too.It seems like it might.
- 儿童的stopPropagation将阻止该事件发生在父(整个祖先)
- 一个孩子的preventDefault将停止这个孩子的事件,但它会发生在它的父母身上(也会发生在祖先身上!)
现在在您的代码中,哪个是父级?哪个孩子?img是孩子tr是父母(老实说是祖父母),所以猜猜stopPropagation代码应该在哪里。
- I get the impression this is wrong.I think stopprogation does not stop the action of the child from happening?
- You're probably talking about preventitdefault,but my comment was aimed at the stopprogation explanation.用户RPS在我的评论之后已经更正了他的回答。
- @Trisped,@user1884155 i s right,the example you're saying seems to be of EDOCX1 universifical 1 nac's.and initially I made the mistake of saying that the EDOCX1 universal 2.will stop any child's events too which was later corrected by@user1884155.
- @user1884155 sorry,copy paste mistake.你们应该有你说的1个音标
W3C事件preventDefault:
The event.preventDefault() method stops the default action of an
element from happening.
For example:
Prevent a submit button from submitting a form Prevent a link from
following the URL
W3C事件stopPropagation:
The event.stopPropagation() method stops the bubbling of an event to
parent elements, preventing any parent event handlers from being
executed.
|