且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

$(document).on()和$(element).on()之间有什么区别

更新时间:2022-01-28 05:07:59

@Mukesh已经回答了主要区别. 我将尝试再添加一件事.

Main difference is already answered by @Mukesh. I will try to add one more thing.

当您在html文档中的元素(例如 div button )上单击(或其他任何事件)时,该单击事件将传播到的父元素该元素.因此,如果您具有这样的结构:

When you click(or any other event) on an element(like div or button) in the html document, that clicking event is propagated to the parent elements of that element. So if you have structure like this:

<div>
    <table>
        <tr>
            <td>
                <button>Click Me</button>
            </td>
        </tr>
    </table>
</dvi>

然后单击按钮,该单击将传播到td,然后传播到tr,然后传播到表,最后传播到文档本身.

and you click on the button, that click will propagate to the td, then to the tr, then to the table and then finally to the document itself.

现在,假设您已在文档( $ document.on('click',...))以及按钮( $(button. on('click',...))),两者都会执行一些不同的操作.然后,如果单击该按钮,则将执行相应的按钮动作,并且还将执行$(document)的相应动作.

Now lets say you have registered a click event on the document($document.on('click',...)) and also on the button($(button.on('click',...))), both of which does some different actions. Then if you click on the button, the corresponding button action will be executed, and also the corresponding action of the $(document) will also be executed.

为防止按钮单击传播到文档本身,您需要对按钮单击处理程序进行操作(例如stopPropagation等)

To prevent the button click to propagate to the document itself, you need to take actions on the button click handler(like stopPropagation etc.)