What is different between $(document).on() and $(element).on()

后端 未结 2 1188
-上瘾入骨i
-上瘾入骨i 2021-02-05 12:55

I know about jquery .on() use and purpose, because I use it.

But I want to know what is the difference between $(document).on() vs $(element).on()

相关标签:
2条回答
  • 2021-02-05 13:34

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

    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>
    

    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.

    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.

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

    0 讨论(0)
  • 2021-02-05 13:44
    $(document).on('click','.btn-edit',function()
    

    This binds a click event to the document and all child elements within it. This method is referred to as delegated event handling.

    $('#table-user').on('click','.btn-edit',function()
    

    binds the click event to the #table-user directly. captures the event directly on the element.

    0 讨论(0)
提交回复
热议问题