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