简体   繁体   English

如何使用javascript获取body标签的值?

[英]How to get the value of a body tag using javascript?

We know that we can get the value from a Form when the user enters some value in some input field, Is there anyway by which we can get the value from the whole body (if user type something on the body)? 我们知道,当用户在某个输入字段中输入某个值时,我们可以从Form中获取值;无论如何,我们是否可以从整个主体中获取值(如果用户在主体上键入内容)? I tried adding onkeyup="behavior()" in the body tag of html page, and JavaScript behind that was 我尝试在HTML页面的body标签中添加onkeyup="behavior()" ,其后的JavaScript是

function behavior()
{
var key = document.body.value;
window.alert(key);
}

It didn't work, i also tried 它没有用,我也尝试过

var key = document.body.innerHTML;

Nothings working, how can i do that? 什么都没用,我该怎么办?

Thanks 谢谢

You can listen to the keyup event on window object. 您可以在window对象上侦听keyup事件。 This will basically catch every key typed on the webpage. 基本上,这将捕获网页上键入的每个键。

 window.onkeyup = function(e){ //old browsers var keyCode = e.which || e.keyCode || e.charCode; var key = String.fromCharCode(keyCode); //modern browsers //var key = e.key; console.log(key); }; 

This is just a keyboard listening event. 这只是一个键盘监听事件。

 document.body.onkeyup = function(e){ var keyCode = e.which || e.keyCode || e.charCode; var key = String.fromCharCode(keyCode); document.getElementById("output").innerHTML += key; } 
 <!DOCTYPE html> <html lang="en"> <head></head> <body> This is the body's content. <div id="output"></div> </body> </html> 

I'm guessing you want to check which key is pressed.. 我猜您想检查按下了哪个键。

 function keypressed(event) { console.log(event.which); } 
 <body onkeyup="keypressed(event);"> </body> 

check console for ascii code of the keypressed. 检查控制台以获取按键的ascii代码。

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

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