JavaScript:代码选择 - 出了什么问题?

时间:2013-04-03 14:22:28

标签: javascript syntax-error selection

<!DOCTYPE html>
<html>
<head>
  <title>Select Code</title>
  <meta charset="UTF-8">
  <script type="text/javascript">
    window.onload = function() {
      function selectCode(a) {

        // Get ID of Code Block
        var e = a.parentNode.parentNode.getElementsByTagName('code')[0];

        // Not IE or IE9+
        if (window.getSelection) {
          var s = window.getSelection();
          if (s.setBaseAndExtent) {
            s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
          }

          // Firefox and Opera
          else {
            if (window.opera && e.innerHTML.substring(e.innerHTML.length - 4) == '<br>') {
              e.innerHTML = e.innerHTML + '&nbsp;';
            }
            var r = document.createRange();
            r.selectNodeContents(e);
            s.removeAllRanges();
            s.addRange(r);
          }
        }

        // Some older browsers
        else if (document.getSelection) {
          var s = document.getSelection();
          var r = document.createRange();
          r.selectNodeContents(e);
          s.removeAllRanges();
          s.addRange(r);
        }

        // IE
        else if (document.selection) {
          var r = document.body.createTextRange();
          r.moveToElementText(e);
          r.select();
        }
      };
    }
  </script>
</head>
<body>
  <a onclick="selectCode(this); return false;" href="#">Select all</a>
  <code>Some Code</code>
</body>
</html>

有人知道出了什么问题吗?它只是不起作用。 : - (

1 个答案:

答案 0 :(得分:1)

我刚删除了window.onload

请在此处查看工作代码http://jsfiddle.net/5n4cw/

<a onclick="selectCode(this);" href="#">Select all</a>
<code>Some Code</code>


<script type='text/javascript'>

 function selectCode(a) {

        // Get ID of Code Block
        var e = a.parentNode.parentNode.getElementsByTagName('code')[0];
        // Not IE or IE9+
        if (window.getSelection) {
          var s = window.getSelection();
          if (s.setBaseAndExtent) {
            s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
          }

          // Firefox and Opera
          else {
            if (window.opera && e.innerHTML.substring(e.innerHTML.length - 4) == '<br>') {
              e.innerHTML = e.innerHTML + '&nbsp;';
            }
            var r = document.createRange();
            r.selectNodeContents(e);
            s.removeAllRanges();
            s.addRange(r);
          }
        }

        // Some older browsers
        else if (document.getSelection) {
          var s = document.getSelection();
          var r = document.createRange();
          r.selectNodeContents(e);
          s.removeAllRanges();
          s.addRange(r);
        }

        // IE
        else if (document.selection) {
          var r = document.body.createTextRange();
          r.moveToElementText(e);
          r.select();
        }
      }

</script>