[英]onclick gives me an error in html. how do I rectify this?
I'm fairly new to JS.我对 JS 很陌生。 In my index.html, I have a button defined as:
在我的 index.html 中,我有一个按钮定义为:
<button id="copyPicture" onclick="copyPage();" class="btn">Copy Page!</button>
and in my script.js, I have:在我的 script.js 中,我有:
function copyPage() {
// Select the entire page
var page = document.body;
var range = document.createRange();
range.selectNode(page);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
// Copy the selected page to the clipboard
document.execCommand('copy');
// Remove the selection
window.getSelection().removeAllRanges();
}
When I inspect the page in Chrome, as soon as I click on the button, I get:当我在 Chrome 中检查页面时,只要单击按钮,我就会得到:
(index):87 Uncaught ReferenceError: copyPage is not defined at HTMLButtonElement.onclick (index):87 Uncaught ReferenceError: copyPage is not defined at HTMLButtonElement.onclick
What am I doing wrong?我究竟做错了什么?
When I click on the button, I am expecting the whole page to get copied to the clipboard so that I can paste it on emails, social medias, etc.当我点击按钮时,我希望整个页面都被复制到剪贴板,这样我就可以将它粘贴到电子邮件、社交媒体等地方。
Based on the error it looks like your JS is not properly included.根据错误,您的 JS 似乎未正确包含在内。
copyPage
function is not available when you click on the button. copyPage
function点击按钮不可用。 The snippet should work.该片段应该有效。
function copyPage() { // Select the entire page var page = document.body; var range = document.createRange(); range.selectNode(page); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); // Copy the selected page to the clipboard document.execCommand('copy'); // Remove the selection window.getSelection().removeAllRanges(); }
<button id="copyPicture" onclick="copyPage();" class="btn">Copy Page!</button> <p>Test text</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.