我有一些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();
这是一个函数调用.不要使用()来分配函数引用.