当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《为什么这个javascriptonclick加载代码运行没有我明确告诉它?》经验,为你挑选了1个好方法。

我有一些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



1> Taplar..:
makeContentView();

这是一个函数调用.不要使用()来分配函数引用.

推荐阅读
雨天是最美
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有