为什么这个javascript onclick加载代码在我没有明确告诉它的情况下运行

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

本文关键字:运行 情况下 javascript onclick 加载 代码 为什么      更新时间:2023-09-26

我有一些javascript可以更改#hash 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该函数——也就是说,您只希望引用该函数,而不是调用它。