event.preventDefault vs event.stopPropagation [英] event.preventDefault vs event.stopPropagation

查看:120
本文介绍了event.preventDefault vs event.stopPropagation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释 event.preventDefault() event.stopPropagation()之间的区别是什么?

Can someone explain what's the difference between event.preventDefault() and event.stopPropagation()?

我有一张桌子,在那张桌子里我有一个img标签。

I have a table and within that table I have an img tag.

当我点击img标签时,我想要看一个弹出窗口。

When I click the img tag, I want to see a popup.

但我也想停止选择多行,所以我使用:

But I also want to stop the selection of multiple rows, so I use:

$("table.items tbody tr").click(function(event) {
        event.stopPropagation();
    });

当我使用js代码时,弹出窗口不会出现;

When I use the js code, the popup does not appear;

如果我删除了js代码,弹出窗口就可以了。

If I delete the js code, the popup works.

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

为什么?

推荐答案

我不是Javascript专家,但据我所知:

I am not a Javascript expert but as far as I know:

使用stopPropagation 确保事件不会起泡链。例如。点击< td> 标记也会点击其父级< tr> 上的点击事件,然后其父< table> 等。 stopPropagation 可防止这种情况发生。

stopPropagation is used to make sure the event doesn't bubble up the chain. eg. a click on a <td> tag would also fire click events on it's parent <tr>, and then its parent <table>, etc. stopPropagation prevents this from happening.

preventDefault 用于停止元素的正常操作,例如。链接上的点击处理程序中的 preventDefault 会停止跟踪链接,或者提交按钮会停止提交表单。

preventDefault is used to stop the normal action of an element, eg. preventDefault in a click handler on a link would stop the link being followed, or on a submit button would stop the form being submitted.

这篇关于event.preventDefault vs event.stopPropagation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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