【问题标题】:EJS File Not Recognizing JavaScript File's CodeEJS 文件无法识别 JavaScript 文件的代码
【发布时间】:2016-10-10 18:03:13
【问题描述】:

我正在创建一个网站,我正在使用 NodeJS 服务器。在我的公用文件夹中,我有一个名为 website.js 的脚本,它具有 jQuery 代码,可在单击 h1 时提供一个 console.log。 (下面的代码)。但是当我在浏览器中单击 h1 时,它不起作用。该文件已正确加载,没有 404 错误,并且我的 CSS 样式表工作正常。

进一步测试:我做了一个简单的测试,看看当我调用它响应的变量(下面的测试代码)时它是否会返回文本:“”(两个引号)所以它一定不能识别它。

//Test code
var xyz = $("#testh1").text();
//jQuery Code
$("#testh1").on("click", function(){
     console.log("Clicked");
});
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="/javascripts/website.js"></script>
    <link rel="stylesheet" type="text/css" href="/stylesheets/website.css">
     <script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="   crossorigin="anonymous"></script>
<title>test</title>
</head>
<body>

 <h1 id="testh1">TEST</h1>

</body>
</html>

【问题讨论】:

    标签: javascript jquery html node.js ejs


    【解决方案1】:
    1. 你需要在你的脚本之前加载 jQuery。

      <script src="https://path-to-jquery"></script>
      <script src="/javascripts/website.js"></script>
      
    2. 在访问其中的任何元素之前,您需要等待 DOM 准备就绪。您可以使用以下代码进行操作:

      $(document).ready(function() {
          $("#testh1").on("click", function(){
               console.log("Clicked");
          });
      });
      

    或者将您的&lt;script&gt;s 放在&lt;body&gt; 的底部,而不是放在&lt;head&gt; 中。

        <script src="https://path-to-jquery"></script>
        <script src="/javascripts/website.js"></script>
    </body>
    

    您在测试代码中得到一个空字符串,因为您的 #testh1 元素尚未加载。

    【讨论】:

    • 我应该在哪个文件中加载 jQuery? JavaScript(website.js) 还是 EJS(website.ejs) 文件?
    • @AnonUser 在 EJS/HTML 中,就像你现在一样。您只需要更改顺序。您不能在 JS 代码中放置 &lt;script&gt; 标记(嗯,至少不是那种格式)。
    • 完美运行!非常感谢!
    猜你喜欢
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    相关资源
    最近更新 更多