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

标签 javascript jquery html ajax window

我有一些 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 函数是无条件触发的。

我只想在单击 6 个带有 class=thumbnailImage 的缩略图之一时调用 makeContentView

最佳答案

makeContentView();

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

关于javascript - 为什么这个 javascript onclick 加载代码在我没有明确告诉它的情况下运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34619340/

相关文章:

javascript - 使用 Node.js 和 MySQL 查询函数回调的范围

javascript - 使用 jquery 更改内部选定元素的功能?

html - 我需要将 JSP 中的字符串转换为 titlecase

javascript - 访问 JSON 对象数组内的变量

javascript - 使用 Javascript 读取服务器端文件

javascript - 默认情况下,JavaScript 中的数组真的是 "sparsed"吗?

javascript - 如何在 jQuery 中获取点击链接的索引?

javascript - 如何在 CSS 或 jQuery 中持续更改按钮的颜色

html - 加载动画不起作用

html - 如何将 Google Maps V3 置于网页中央?