如何在此代码中调用函数?

时间:2014-05-01 14:47:34

标签: javascript jquery

我无法理解执行顺序在这里:

 <script>
  $(function(){
    function f(id){
       document.body.innerHTML  += "<p>executing handler for div " + id + "</p>";
    }

    document.getElementById("div1").onclick = function(){
      f("1");
    }

    document.getElementById("div2").onclick = function(){
      f("2");
    }

    document.getElementById("div3").onclick = function(){ 
      f("3");
    }
  });
</script>

我想知道的是&#39;功能&#39;和&#39; f&#39;叫做?是否有人点击“div”&#39; div然后函数被调用?如果是这样,为什么功能在&#34; =&#34;的右侧?运营商?

5 个答案:

答案 0 :(得分:2)

当有人点击div1时,onclick方法会触发函数f,其值为1。单击div2 / 3时同样,使用这些值调用f

所有f都会更改页面内容以显示消息。

我不确定为什么这会使用document.body.innerHTML,但我通常希望看到显示消息的div,例如document.getElementById('message').innerHTML

我有一种感觉(没有检查)document.body.innerHTML会将页面的整个内容更改为f输出的值。我怀疑这是理想的结果。

答案 1 :(得分:1)

在评论中逐行解释:

 <script>

  // this is a jQuery shorthand for $(document).ready. That means, that this function is executed automatically, when the DOM is ready
  $(function(){

    // declaration of a function that will be executed when it's called from somewhere. 'id' is an argument that can be passed
    function f(id){
       document.body.innerHTML  += "<p>executing handler for div " + id + "</p>";
    }

    // 'onclick' is an event handler. When you click the div container with the id 'div1', then the function, set after '=', gets executed
    document.getElementById("div1").onclick = function(){

      // call the function that you declared above with the argument "1"
      f("1");
    }

    document.getElementById("div2").onclick = function(){
      f("2");
    }

    document.getElementById("div3").onclick = function(){ 
      f("3");
    }
  });
</script>

答案 2 :(得分:1)

如果我根据您的“为什么功能位于=运营商右侧?”的问题正确理解您,则您的问题与以下代码中的= function(){确实相关。< / p>

document.getElementById("div1").onclick = function(){
  f("1");
}

此代码正在执行的操作是将匿名函数分配给onclick元素的div1属性。

当用户点击div1元素时,将执行此匿名函数。在匿名函数中,调用函数f传递字符串"1"

需要匿名功能的原因是因为如果你要排除这个并且只是这个:

document.getElementById("div1").onclick = f("1");

不是在单击元素时调用f函数,而是立即调用f函数并将返回值(未定义)设置为onclick属性。通过将其包装在匿名函数中,您可以获得在单击元素时使用给定参数调用f所需的效果。

答案 3 :(得分:0)

根据你的要求

$(function(){

});

在页面加载时执行

如果你想调用函数f(),你需要调用

$(function(){
f();
});

答案 4 :(得分:0)

$(function(){...}jQuery function for document.ready。所有DOM准备就绪后立即执行此功能。这是jQuery的一个特性。你没有明确地调用它--jQuery会为你处理它。

f()函数附加到为三个div元素定义的单击处理程序(onclick)。单击它们后,它们会触发f()功能。

该函数位于赋值的右侧,因为代码实际上说的是将默认的onclick函数替换为已定义的函数。

相关问题