为什么这个 javascript onclick 加载代码 运行 没有我明确告诉它?

Why does this javascript onclick load code run without me explicitly telling it to?

我有一些 javascript 可以更改 # 散列 URL 并使用 AJAX.

将一些 HTML 加载到元素中
// Manually trigger a hashchange to start the app.
$(window).trigger('hashchange');


function makeContentView() {
  document.location.hash = "content";
  return false; // we don't want event propagation - just AJAX call
}


$(function () {

  $(window).on('hashchange', function () {
    // On every hash change the render function is called with the new hash.
    // This is how the navigation of our app happens.
    render(window.location.hash);
  });

  function render(url) {
    // This function decides what type of page to show 
    // depending on the current url hash value.

    switch (url) {
      case "#home":
        $("#AJAX_Parent").load("body/index_body.html #AJAX_Child");
        break;
      case "#grid":
        $("#AJAX_Parent").load("body/grid_body.html #AJAX_Child", function () {

            var contents = document.getElementsByClassName("thumbnailImage");

              for (i = 0; i < contents.length; i++) {

                // THIS FUNCTION GETS CALLED WITHOUT ME CLICKING
                contents.item(i).onclick = makeContentView();
              }

          }); // makeContentView IS ALWAYS BEING CALLED IMMEDIATELY
    ... // More switch options

^ 请注意,在上面的示例中,"contents.item(i).onclick = makeContentView();" 将 makeContentView 函数分配给我页面缩略图的 onclick 处理程序,但此 makeContentView 函数是无条件触发的。

我只希望在单击具有 class=thumbnailImage

的 6 个缩略图之一时调用 makeContentView
makeContentView();

这是一个函数调用。省略 () 以分配函数引用。

因为你正在调用它,所以简单地制作它

contents.item(i).onclick = makeContentView; //remove the parenthesis from the end

() 放在函数名称之后,您可以立即调用它。删除它们以将函数分配为 onclick 处理程序(您现在正在分配其结果)。

你想要 contents.item(i).onclick = makeContentView 没有 括号。原因是 Javascript 基本上 运行 任何它找到的以 () 结尾的函数 一旦它读取它 .

你不希望Javascript到运行这个函数一读到它。相反,您只想告诉 Javascript 关于函数的信息——也就是说,您只想 reference 函数,而不是 call它。