JSFiddle 示例在网络上工作但在我的电脑上不工作

JSFiddle example working on web but is not working on my pc

我正在寻找 google 一个用于复制输入字段的脚本,然后遇到了这个:

https://jsfiddle.net/9q3c1k20/

我的例子:

    document.getElementById("copy-text").onclick = function() {
      this.select();
      document.execCommand('copy');
      alert('This is a test...');
    }
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script src="http://code.jquery.com/jquery-1.11.0.js"></script>
    </head>
    
    <body>
    <input id="copy-text" type="text" value="Select a part of this text!">
    </body>
    </html>

选择 #copy-text 的脚本是 运行 在文档正文(和输入元素)被解析之前。将脚本移至正文底部:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.11.0.js"></script>
</head>

<body>
<input id="copy-text" type="text" value="Select a part of this text!">
<script>
document.getElementById("copy-text").onclick = function() {
  this.select();
  document.execCommand('copy');
  alert('This is a test...');
}
</script>
</body>
</html>

但是将你的脚本放在一个单独的 .js 文件中并只给它 defer 属性会更优雅:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script src="myscript.js" defer></script>
</head>
<body>
<input id="copy-text" type="text" value="Select a part of this text!">
</body>
</html>