这些语法有什么区别请详细解释?

What is diffrent between these syntax please Explain in details?

请详细解释这些语法有什么区别?

$(document).on("click", "#index1", function() {
    $(p).hide();
});
$("#index2").on("click", "#index1", function() {
    $(p).hide();
});
$("#index1").on("click", function() {
    $(p).hide();
});

在第一种情况下,您将点击侦听器添加到 "document",但仅当您点击“#index1”时才会执行。 第二步 - 您将侦听器添加到 "index2" 并且仅当您单击位于“#index2”内的“#index1”时才会执行它。 在第三种情况下,您只需将侦听器添加到 "index1"

首先让我们想象一个网页。

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>

<body>
    <button id='index1'>click me</button>
</body>

</html>
  1. 这会起作用
<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>

<body>
    <button id='index1'>click me</button>
    <script type="text/javascript">
        $("#index1").on("click", function () {
            $(p).hide();
        });
    </script>
</body>

</html>
  1. 这是行不通的,因为执行脚本时该元素不存在。
<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>

<body>
    <script type="text/javascript">
        $("#index1").on("click", function () {
            $(p).hide();
        });
    </script>
    <button id='index1'>click me</button>
</body>

</html>

但如果有解决方法,它会

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript">
        $(document).on("click", "#index1", function() {
            $(p).hide();
        });
    </script>
    <button id='index1'>click me</button>
</body>
</html>

这表示每当在文档上触发点击事件时检查是否在 #index1 元素上触发了点击。所以即使,元素不存在回调,也附加到文档节点。现在,只要点击文档,它就会检查它是否来自 #index1