【问题标题】:What is diffrent between these syntax please Explain in details?这些语法有什么区别,请详细解释一下?
【发布时间】:2017-03-04 22:04:49
【问题描述】:

这些语法有什么不同,请详细解释一下?

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

【问题讨论】:

  • ^ 那里都有详细的解释。
  • Stack 不是学校或教程网站。这是您来寻求帮助以解决您遇到的代码问题的地方,这在我看来是代码的有效语法。另外,由于您没有提到恕我直言不符合问题,那么您可以阅读并从手册中学习,尝试一些东西,如果有些东西不起作用,然后回来发布一个(真正的)问题。
  • 另外,没有我删除的标记为(编辑)的 php。

标签: javascript jquery ajax jquery-mobile


【解决方案1】:

在第一种情况下,您将单击侦听器添加到“文档”,但仅当您单击“#index1”时才会执行。 其次 - 您将侦听器添加到“index2”,只有当您单击位于“#index2”内的“#index1”时才会执行它。 在第三种情况下,您只需将侦听器添加到“index1”

【讨论】:

  • 谢谢...顺便说一句,我第二次感到困惑。现在清除
【解决方案2】:

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

<!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

【讨论】:

    猜你喜欢
    • 2016-07-25
    • 2018-11-06
    • 2012-11-21
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多