为什么这个javascript onclick加载代码在我没有明确告诉它的情况下运行
Why does this javascript onclick load code run without me explicitly telling it to?
我有一些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该函数——也就是说,您只希望引用该函数,而不是调用它。
相关文章:
- 如何在没有单词的情况下从命令行运行Node.js程序'节点'
- 在php中不运行java脚本的情况下重定向页面
- 在禁用浏览器flash插件的情况下运行Karma测试
- 在不加载页面的情况下运行javascript
- CSS转换获胜't在没有“setTimeout”的情况下运行
- CSS 转换不会在没有 setTimeout 的情况下运行
- 我的javascript不会在没有警报的情况下运行
- Apache Cordova:在不启动浏览器应用程序的情况下运行Cordova运行浏览器
- 强pm不会在NODE_ENV=生产的情况下运行
- Javascript在不打算运行的情况下运行多次
- 在不安装Zend优化器的情况下运行php文件
- 如何在没有缓存/cookie的情况下运行/调试Web应用程序项目
- 仅在尚未运行jQuery UI的情况下运行动画
- 如何在不停止的情况下永远运行node-js
- 如何在启用ES6功能的情况下运行Node.js应用程序
- 如何在没有网络工作者的情况下运行多个脚本
- 可以插入<脚本>标记可以在不使用JavaScript中的eval的情况下多次运行
- 节点包因果报应没有在没有信息的情况下运行
- 在不重新运行jquery验证的情况下检查表单是否有效
- Bxslider预加载程序在没有图像的情况下以无限循环运行