Javascript代码从内联文件移动到外部文件时会产生错误

Javascript code produces errors when moved from inline to external file

本文关键字:文件 错误 外部 移动 代码 Javascript      更新时间:2023-09-26

我有一个内置到我正在工作的页面的复制脚本,当复制JS内联时,它工作得很好,但只要我将其移到外部,它就会产生以下错误:copy.js:1 Uncaught TypeError: Cannot read property 'addEventListener' of null

我不确定为什么,因为当内联没有问题。段代码的副本为:

    <?php
$connect = mysqli_connect("localhost", "brandina_templat", "REMOVED", "brandina_templates");  
$catresult = "SELECT * FROM categories";
$catquery = mysqli_query($connect,$catresult);
$catquery2 = mysqli_query($connect,$catresult);
?>
<html>  
      <head>  
           <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
           <title>Templates Sheet | Brandin Arsenault's</title>    
           <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
           <script src="js/bootstrap.js"></script>  
           <script src="js/tabcontent.js"></script> 
           <link href="css/bootstrap.css" rel="stylesheet" />  
      </head>   
      <body>  
       <div class="container">  
                <br />  
                <h1 align="center">Templates Sheet</h1>
                    <center><ul class="tabs">
<?php
    if(!$catquery)
    {
        die('Invalid query: ' . mysql_error());
    }
        while($row = mysqli_fetch_array($catquery))
        {
            $number=$row['number'];
            $tabname=$row['tabname'];
            $catname=$row['catname'];
            echo "<li class='tab-link' data-tab='$tabname'>$catname</li>";
        }
?>
        </ul>
<?php
    if(!$catquery2)
    {
        die('Invalid query: ' . mysql_error());
    }
        while($row = mysqli_fetch_array($catquery2))
        {
            $number=$row['number'];
            $tabname=$row['tabname'];
            $catname=$row['catname'];
            $result = "SELECT * FROM templates WHERE category=$number";
            $query = mysqli_query($connect,$result);
            echo "<div id='$tabname' class='tab-content'>
                                        <table><center>";
                    $c = 0;
                    $n = 3;
                if(!$query)
                    {
                        die('Invalid query: ' . mysql_error());
                    }
                        while($row = mysqli_fetch_array($query))
                            {
                                $id=$row['id'];
                                $longname=$row['longname'];
                                $shortname=$row['shortname'];
                                $text=$row['text'];
                                    if($c % $n == 0 && $c != 0)
                                        {
                                            echo '</tr><tr>';
                                        }
                                    $c++;
                                    echo "
                                        <td>
                        <center><b>$longname</b></center><textarea id='$id' cols='25' rows='3'>$text</textarea><br /><button id='$shortname'>Copy</button>
                                        </td>
                                        <script>
                                            var shortname = '$shortname';
                                        </script>";
                            }
            echo "</center></table></div>";
        }
?>
<script src='js/copy.js'></script>
</center>
</div>
</body>
</html>

copy.js是:

    document.getElementById(shortname).addEventListener('click', function() {
    copyToClipboardMsg(document.getElementById('$id'), 'msg');
});
function copyToClipboardMsg(elem, msgElem) {
      var succeed = copyToClipboard(elem);
    var msg;
    if (!succeed) {
        msg = 'Copy not supported or blocked.  Press Ctrl+c to copy.'
    } else {
        msg = 'Text copied to the clipboard.'
    }
    if (typeof msgElem === 'string') {
        msgElem = document.getElementById(msgElem);
    }
    msgElem.innerHTML = msg;
    setTimeout(function() {
        msgElem.innerHTML = '';
    }, 2000);
}
function copyToClipboard(elem) {
      // create hidden text element, if it doesn't already exist
    var targetId = '_hiddenCopyText_';
    var isInput = elem.tagName === 'INPUT' || elem.tagName === 'TEXTAREA';
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
        // can just use the original source element for the selection and copy
        target = elem;
        origSelectionStart = elem.selectionStart;
        origSelectionEnd = elem.selectionEnd;
    } else {
        // must use a temporary form element for the selection and copy
        target = document.getElementById(targetId);
        if (!target) {
            var target = document.createElement('textarea');
            target.style.position = 'absolute';
            target.style.left = '-9999px';
            target.style.top = '0';
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = elem.textContent;
    }
    // select the content
    var currentFocus = document.activeElement;
    target.focus();
    target.setSelectionRange(0, target.value.length);
    // copy the selection
    var succeed;
    try {
          succeed = document.execCommand('copy');
    } catch(e) {
        succeed = false;
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === 'function') {
        currentFocus.focus();
    }
    if (isInput) {
        // restore prior selection
        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
        // clear temporary content
        target.textContent = '';
    }
    return succeed;
}

提前感谢!

当您使用内联代码时,变量$shortname存在,但当您将代码移到外部时,它不再存在。

你可以使用:

<script>
    var shortname = '$shortname';
</script>
<script src='js/copy.js'></script>
在你的copy.js文件中,你应该使用:
document.getElementById(shortname).addEventListener('click', function() {

否则- javascript代码正在寻找的元素,它的id是$shortname,你没有真正有一个值。