简体   繁体   English

为什么这些 OnClick 和 OnKeyDown 事件不起作用?

[英]Why don't these OnClick and OnKeyDown Events work?

 var clicks; var time1; var keys_pressed; var keys_typed; function startTrack() { time1 = Date.now(); clicks = 0; keys_pressed = 0; keys_typed = 0; } document.onclick = function() { clicks++; }; document.onkeydown = function() { keys_pressed++; }; function analytics() { var time2 = Date.now(); var time = time2 - time1; var min = Math.floor(time / 60000); var sec = (time % 60000) / 1000; document.body.insertAdjacentHTML( 'afterbegin', '<div hidden><p>Number of mouse clicks: '+ clicks + '</p><p>Total time spent: ' + min + ' mins, ' + sec + ' secs' + '</p><p>Total key presses: ' + keys_pressed + '</p><p>Total number of characters: ' + keys_typed + '</p></div>' ); }
 <body onload="startTrack()">... </body>

I'm a complete JS beginner trying to get 2 simple events to work without using Ajax or JQuery or anything like that.我是一个完整的 JS 初学者,试图在不使用 Ajax 或 JQuery 或类似的东西的情况下让 2 个简单的事件工作。 All my other scripts seem to work, except the two events above where I'm just trying to store the number of keys pressed and mouse clicks anywhere on the page .我的所有其他脚本似乎都有效,除了上面的两个事件,我只是试图在页面上的任何位置存储按下的键数和鼠标点击数。 However, the counters for both these metrics remain at zero no matter what.但是,无论如何,这两个指标的计数器都保持为零。 Any help would be greatly appreciated.任何帮助将不胜感激。

Doing a clicks++; clicks++; when it is not initialized produces NaN since you cannot ++ on undefined .当它未初始化时会产生NaN ,因为您不能在undefined上使用++

 var clicks; var time1; var keys_pressed; var keys_typed; function startTrack() { time1 = Date.now(); clicks = 0; keys_pressed = 0; keys_typed = 0; } document.onclick = function() { clicks++; // without the initialization this logs NaN console.log("Clicks:",clicks); }; document.onkeydown = function() { keys_pressed++; console.log("Pressed:", keys_pressed); }; console.log(clicks);// logs "undefined" // you need to initialize your variables so call it; //startTrack();
 <body onload="startTrack()">...<div>Hi there I am here. But the fish ate my bait.</div> </body>

Using addEventListener() is better as it allows you to add multiple listeners instead of replacing a listener that might have already been there:使用addEventListener()更好,因为它允许您添加多个侦听器而不是替换可能已经存在的侦听器:

 let events = 0 const foo = document.getElementById('foo') document.addEventListener('click', oneMore) document.addEventListener('keydown', oneMore) function oneMore(ev) { foo.textContent = ++events }
 #foo { width: 50px; height: 50px; background: lime; }
 <div id=foo>Click me</div>

addEventListener('click', (e) => { clicks++ })
addEventListener('keydown', (e) => { keys_pressed++ })

Should work.应该管用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM