简体   繁体   English

如何使用 JavaScript 在单击按钮时提醒页面的所有内容

[英]How to alert all content of page on button click with JavaScript

I need to get all the content of page including all codes on JavaScript alert.我需要获取页面的所有内容,包括JavaScript警报上的所有代码。 Please check the code.请检查代码。

 function getContent() { var content = document.getElementsByTagName('html').value; alert(content); }
 <html> <head> </head> <body> Some more code.......... <a href="#" onclick="getContent()">Get Content</a> </body> </html>

I am trying to execute the function from inside the page and trying to get the value.我正在尝试从页面内部执行该函数并尝试获取该值。 It is giving me undefined error它给了我undefined错误

.getElementsByTagName() returns a NodeList collection of elements. .getElementsByTagName()返回一个NodeList元素集合。 You need to access the first index with [0] . 您需要使用[0]访问第一个索引。 In addition to this, it does not have a .value property. 除此之外,它没有.value属性。 You're looking for .innerHTML instead. 您正在寻找.innerHTML

Note that you also shouldn't make use of onclick , and instead should make use of unobtrusive JavaScript by adding an event listener . 请注意,您也不应使用onclick ,而应通过添加事件侦听器来使用不引人注目的JavaScript

This can be seen in the following: 可以在以下内容中看到:

 function getContent() { var content = document.getElementsByTagName('html')[0].innerHTML; alert(content); } document.getElementsByTagName('a')[0].addEventListener('click', getContent); 
 <html> <head></head> <body> Some more code.......... <a href="#">Get Content</a> </body> </html> 

Note: this will not work as expected in a Fiddle, but will work as expected on a proper website. 注意:这在Fiddle中无法正常工作,但在适当的网站上将正常工作。

This can be achieved via the innerHTML field of a DOM element. 这可以通过DOM元素的innerHTML字段来实现。 Consider making the following changes to your getContent() function: 考虑对getContent()函数进行以下更改:

 function getContent() { var { innerHTML } = document.querySelector('html'); alert(innerHTML); } 
 <html> <head> </head> <body> Some more code.......... <p> and some more content </p> <a href="#" onclick="getContent()">Get Content</a> </body> </html> 

Try this:- 尝试这个:-

<html>
<head>
<script>
function getContent() { var content = document.getElementsByTagName('html')[0].innerHTML;
alert("<html>"+content+"</html>"); }
</script>
</head>
<body>
Some more code.......... <a href="#" onclick="getContent()">Get Content</a>
</body>
</html>

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

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